JavaScript函数


函数是一组可重用的代码,可以在程序中的任何位置调用。这消除了一次又一次编写相同代码的需要。它可以帮助程序员编写模块化代码。函数允许程序员将一个大型程序划分为许多小的和可管理的函数。

与任何其他高级编程语言一样,JavaScript也支持使用函数编写模块化代码所需的所有函数。你一定已经看过类似的函数alert()write()在前面的章节中。我们一次又一次地使用这些函数,但是它们只用核心JavaScript编写过一次。

JavaScript允许我们也编写我们自己的函数。本节说明如何使用JavaScript编写自己的函数。

函数定义


在使用函数之前,我们需要对其进行定义。在JavaScript中定义函数的最常见方法是使用function关键字,后跟一个唯一的函数名,一个参数列表(可能为空)以及一个用花括号括起来的语句块。

语法

基本语法如下所示。

<script type = "text/javascript">
    <!--
        function functionname(parameter-list) {
            statements
        }
    //->
</script>

请尝试以下示例。它定义了一个名为sayHello的函数,该函数不带任何参数:

<script type = "text/javascript">
    <!--
        function sayHello() {
            alert("Hello there");
        }
    //->
</script>

调用函数


要在脚本后面的某个地方调用一个函数,你只需要编写该函数的名称,如下面的代码所示。

<html>
    <head>
        <script type = "text/javascript">
            function sayHello() {
                document.write ("Hello there!");
            }
        </script>
      
    </head>
   
    <body>
        <p>Click the following button to call the function</p>
        <form>
            <input type = "button" onclick = "sayHello()" value = "Say Hello">
        </form>
        <p>Use different text in write method and then try...</p>
    </body>
</html>

函数参数


到目前为止,我们已经看到了没有参数的函数。但是有一种在调用函数时传递不同参数的函数。这些传递的参数可以在函数内部捕获,并且可以对这些参数进行任何操作。一个函数可以接受多个参数,并用逗号分隔。

请尝试以下示例。我们已经修改了sayHello在这里起作用。现在,它需要两个参数。

<html>
    <head>
        <script type = "text/javascript">
            function sayHello(name, age) {
                document.write (name + " is " + age + " years old.");
            }
        </script>
    </head>
   
    <body>
        <p>Click the following button to call the function</p>
        <form>
            <input type = "button" onclick = "sayHello('Zara', 7)" value = "Say Hello">
        </form>
        <p>Use different parameters inside the function and then try...</p>
    </body>
</html>

返回声明


JavaScript函数可以具有可选的return语句。如果要从函数返回值,这是必需的。该语句应该是函数中的最后一条语句。

例如,你可以在一个函数中传递两个数字,然后可以期望该函数在你的调用程序中返回它们的乘法。

请尝试以下示例。它定义了一个函数,该函数接受两个参数并将它们连接起来,然后再将结果返回到调用程序中。

<html>
    <head>
        <script type = "text/javascript">
            function concatenate(first, last) {
                var full;
                full = first + last;
                return full;
            }
            function secondFunction() {
                var result;
                result = concatenate('Zara', 'Ali');
                document.write (result );
            }
        </script>
    </head>
   
    <body>
        <p>Click the following button to call the function</p>
        <form>
            <input type = "button" onclick = "secondFunction()" value = "Call Function">
        </form>
        <p>Use different parameters inside the function and then try...</p>
  </body>
</html>

关于JavaScript函数,有很多知识要学习,但是,我们已经在本教程中介绍了最重要的概念。

  • JavaScript嵌套函数

  • JavaScript Function()构造函数

  • JavaScript函数文字