Javascript 简明教程

JavaScript - Functions

JavaScript 中的 function 是可以在程序中任何地方调用的可重用代码块。它消除了反复编写相同代码的需要。它帮助程序员编写模块化代码。函数允许程序员将大型程序划分为多个小而易于管理的函数。

A function in JavaScript is a group of reusable code that can be called anywhere in your program. It eliminates the need of writing the same code again and again. It helps programmers in writing modular codes. Functions allow a programmer to divide a big program into a number of small and manageable functions.

与其他高级编程语言一样,JavaScript 也支持使用函数编写模块化代码所需的一切功能。你一定在前面的章节中看到过 alert()write() 这样的函数。我们一直在反复使用这些函数,但是它们只在核心 JavaScript 中被编写过一次。

Like any other advanced programming language, JavaScript also supports all the features necessary to write modular code using functions. You must have seen functions like alert() and write() in the earlier chapters. We were using these functions again and again, but they had been written in core JavaScript only once.

JavaScript 也允许我们编写自己的函数。本节介绍如何在 JavaScript 中编写自己的函数。

JavaScript allows us to write our own functions as well. This section explains how to write your own functions in JavaScript.

Function Definition

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

Before we use a function, we need to define it. The most common way to define a function in JavaScript is by using the function keyword, followed by a unique function name, a list of parameters (that might be empty), and a statement block surrounded by curly braces.

所有需要在函数调用中执行的语句都必须写在花括号内。

All statements you need to execute on the function call must be written inside the curly braces.

Syntax

在 JavaScript 中定义函数的基本语法如下−

The basic syntax to define the function in JavaScript is as follows −

function functionName(parameter-list) {
    statements
}

这种类型的函数定义称为函数声明或函数语句。我们还可以使用函数表达式定义函数。我们将在下一章详细讨论函数表达式。

This type of function definition is called function declaration or function statement. We can also define a function using function expression. We will discuss function expression in details in the next chapter.

以下示例定义了一个名为 sayHello 的函数,该函数不接受任何参数−

The following example defines a function called sayHello that takes no parameter −

function sayHello() {
    alert("Hello there");
}

Function Expression

JavaScript 中的函数表达式允许您将函数定义为表达式。函数表达式类似于匿名函数声明。函数表达式可以赋值给变量。

The Function expression in JavaScript allows you to define a function as an expression. The function expression is similar to the anonymous function declaration. The function expression can be assigned to a varaible.

JavaScript 中函数表达式的语法如下–

The syntax of function expression in JavaScript is as follows–

const varName = function (parameter-list) {
    statements
};

在下面的示例中,我们使用函数表达式定义了一个 JavaScript 函数,并将其赋给变量名 myFunc。

In the example below, we have defined a JavaScript function using function expression and assigned it to a vriable name myFunc.

const myFunc = function (x, y){
   return x + y;
};

Calling a Function

要在脚本的某个地方稍后调用函数,您只需编写该函数的名称,后面加上圆括号 (),如下面的代码所示。

To invoke a function somewhere later in the script, you would simply need to write the name of that function with the parantheses () as shown in the following code.

Example

下面的代码显示了输出中的按钮。当您单击按钮时,它将执行 sayHello() 函数。sayHello() 函数在输出中打印“Hello there!”信息。

The below code shows the button in the output. When you click the button, it will execute the sayHello() function. The sayHello() function prints the "Hello there!" message in the output.

<html>
<head>
   <script type="text/javascript">
      function sayHello() {
         alert("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 the write method and then try... </p>
</body>
</html>

Function Parameters

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

Till now, we have seen functions without parameters. But there is a facility to pass different parameters while calling a function. These passed parameters can be captured inside the function and any manipulation can be done over those parameters. A function can take multiple parameters separated by comma.

Example

尝试以下示例。我们在此处修改了 sayHello 函数。现在它接受两个参数。

Try the following example. We have modified our sayHello function here. Now it takes two parameters.

<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>

The return Statement

JavaScript 函数可以具有可选的 return 语句。如果您想从函数中返回值,则需要此语句。此语句应该是函数中的最后一个语句。

A JavaScript function can have an optional return statement. This is required if you want to return a value from a function. This statement should be the last statement in a function.

例如,您可以将两个数字传递给函数,然后您希望该函数在调用程序中返回它们的乘积。

For example, you can pass two numbers in a function, and then you can expect the function to return their multiplication in your calling program.

Example

下面的代码定义了一个在调用程序中返回结果之前连接两个参数的函数。另外,您可以了解它如何使用 return 语句返回值。

The code below defines a function that concatenates two parameters before returning the resultant in the calling program. Also, you may take a look that how it returns the value using the return statement.

<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');
         alert(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>

Functions as Variable Values

在 JavaScript 中,函数可以与其他变量相同的方式使用。因此 JavaScript 被称为具有头等函数。函数可以作为参数传递给其他函数。

In JavaScript, functions can be used same as other variables. That’s why JavaScript is said to have a first-calss functions. The functions can be passed as arguments to the other functions.

Example

在下面的示例中,我们使用函数表达式声明了一个函数,并使用该函数与另一个字符串连接。

In the example below, we have declared a function using function expression and use the function to concatenate with other string.

<html>
<body>
   <div id = "output"> </div>
   <script>
      const myFunc = function (){ return "Hello ";};
      document.getElementById("output").innerHTML = myFunc() + "Users.";
  </script>
</body>
</html>

我们已在单独的章节中讨论了两个重要概念。

We have covered two important concepts in separate chapters.