Although a function is defined only once, a JavaScript program can execute or invoke it any number of times.

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

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.

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:
function square(x) { return x*x; }

it can be defined with a function literal:
var square = function(x) { return x*x; }


《JavaScript权威指南(影印版)(第5版)》 《JavaScript权威指南(第5版)》

Powered by WordPress | Theme by ck web design | TOP 顶部
Copyright © 崔凯 All rights reserved. 蜀ICP备12025891号.