1. 函数定义
var f = function fact(x) { if (x <= 1) return 1; else return x*fact(x-1); };
这样外部可以调用f(5) 但是不能调用fact(5);
去掉var f = 则可以直接在外部调用fact(5);
This line of codedefines an unnamed function and stores a reference to it in the variable f. It does not actually create a function named fact( ), but it does allow the body of the function to refer to itself using that name. Note, however, that this type of named function literal is not properly implemented before JavaScript 1.5.
2. 像变量一样使用函数
var a =square(4); // a contains the number 16
var b = square; // Now b refers to the same function thatsquare does
var c = b(5); // c contains the number 25
3. 函数参数 callee
In addition to itsarray elements, the Arguments object defines a callee property that refers tothe function that is currently being executed. This is useful, for example, toallow unnamed functions to invoke themselves recursively. For instance, here isan unnamed function literal that computes factorials:
function(x) {
if (x <= 1) return 1;
return x * arguments.callee(x-1);
}
Throughout this section we've been referring to the "arguments array." Keep in mind,however, that arguments is not really an array; it is an Arguments object. Each Arguments object defines numbered array elements and a length property, but it is not technically an array -- it is better to think of it as an object that happens to have some numbered properties
function f(x) {
alert(x); // Displays the initial value ofthe argument
arguments[0] = null; // Changing the array element also changes x
alert(x); // Now displays "null"
}
4. 函数call 和apply
f.call(o, 1, 2);
This is similar tothe following lines of code:
o.m = f;
o.m(1,2);
delete o.m;
The apply( ) methodis like the call( ) method, except that the arguments to be passed to thefunction are specified as an array:
f.apply(o, [1,2]);