Functionsˈfʌŋkʃən函数

Although a function is defined only once, a JavaScript program can execute or invoke it any number of times.
虽然函数只定义一次,但是JavaScript程序却可以多次执行或调用它。

A function may be passed arguments, or parameters, specifying the value or values upon which it is to perform its computation, and it may also return a value that represents the results of that computation.
函数可以带有实际参数或形式参数,用于指定这个函数执行计算要使用的一个或多个值,而且它还能返回一个值,以表示计算结果。

JavaScript implementations provide many predefined functions, such as the Math.sin() function that computes the sine of an angle.
JavaScript 的实现提供了许多预定义函数,如 Math.sin() ,它用于计算角的正弦值。

JavaScript programs may also define their own functions with code that looks like this:
JavaScript 程序也可以定义自己的函数,代码如下:

function square(x)//定义了一个名为square的函数,它指定了一个参数x
{
return x*x; // 返回参数x的平方(值)
}

Once a function is defined, you can invoke it by following the function’s name with an optional comma-separated list of arguments within parentheses. The following lines are function invocations:
一旦定义了函数,只需要在函数名后边加上一个可选的、用逗号分隔的参数列表(该列表用括号括起来),就可以调用它。下面是函数调用的代码:


y = Math.sin(x);
y = square(x);
d = compute_distance(x1,y1,z1,x2,y2,z2);
move();

An important feature of JavaScript is that functions are values that can be manipulated by JavaScript code.
JavaScript 的一个重要特性是 JavaScript 代码可以对函数进行操作。

The fact that functions are true values in JavaScript gives a lot of flexibility to the language.
JavaScript 中的函数是真正的数值,这一点给语言带来了很大的灵活性。

It means that functions can be stored in variables, arrays, and objects, and it means that functions can be passed as arguments to other functions.
这就意味着函数可以被存储在变量、数组和对象中,而且函数还可以作为参数传递给其他函数。

Functions Literals 函数直接量

A function literal is defined with the function keyword, followed by an optional function name, followed by a parenthesized list of function arguments, and then the body of the function within curly braces.
函数直接量是用关键字function后加可选的函数名、用括号括起来的参数列表和用花括号括起来的函数体定义的。

In other words, a function literal looks just like a function definition, except that it does not have to have a name.
简而言之,函数直接量看起来就像个函数定义,只不过没有函数名。

The big difference is that function literals can appear within other JavaScript expressions.
它们之间最大的差别是函数直接量可以出现在其他 JavaScript 表达式中。

Thus, instead of defining the function square() with a function definition:
因此,除了用函数定义来定义函数square()
function square(x) { return x*x; }

it can be defined with a function literal:
还可以用函数直接量来定义它:
var square = function(x) { return x*x; }

Referenceˈrefrəns参考

《JavaScript权威指南》