`

javascript匿名函数(另附JavaScript: The Definitive Guide, 5th Edition.chm)

阅读更多

 

8.1.2. Function Literals

JavaScript allows functions to be defined with function literals. As discussed in Chapter 3, a function literal is an expression that defines an unnamed function. The syntax for a function literal is much like that of the function statement, except that it is used as an expression rather than as a statement and no function name is required. The following two lines of code define two more or less identical functions using a function statement and a function literal, respectively:

function f(x) { return x*x; }              // function statement
var f = function(x) { return x*x; };       // function literal

 

Although function literals create unnamed functions, the syntax allows a function name to be optionally specified, which is useful when writing recursive functions that call themselves. For example:

var f = function fact(x) { if (x <= 1) return 1; else return x*fact(x-1); };

 

This line of code defines an unnamed function and stores a reference to it in the variable f. It does not store a reference to the function into a variable 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 was not properly implemented before JavaScript 1.5.

Because function literals are created by JavaScript expressions rather than statements, they are quite flexible and are particularly well suited for functions that are used only once and need not be named. For example, the function specified by a function literal expression can be stored into a variable, passed to another function, or even invoked directly:

f[0] = function(x) { return x*x; };  // Define a function and store it
a.sort(function(a,b){return a-b;});  // Define a function; pass it to another
var tensquared = (function(x) {return x*x;})(10);  // Define and invoke

 

 

8.1.2 匿名函数

 

JavaScript允许函数声明为匿名函数,匿名函数是一个无名子的函数表达式,匿名函数的语法非常像函数的声明语句,当然,除了其是一个表达式而不是声明语句和没有函数名之外。以下两行代码声明了类似的同一函数,一个使用函数声明语句function,一个使用匿名函数

 

function f(x) { return x*x; } // function statement

var f = function(x) { return x*x; }; // function literal

 

虽然匿名函数创建了一个无名称的函数,但是语法允许可选择标示函数名,当写自调用的递归函数的时候,这个是非常有用的,例如:

 

var f = function fact(x) { if (x <= 1) return 1; else return x*fact(x-1); };

这行代码声明了一个匿名函数,并将该函数的引用存储在变量f中,它不能将函数引用存储在fact的变量中,但允许函数体

内使用fact名字调用其自身,注意,虽然如此,但匿名函数类型在JavaScript 1.5版本以前是不支持的

 

因为匿名函数是作为JavaScript表达式创建的而不是声明语句,所以他们是非常灵活的,尤其适合仅使用一次无需命名的场合,例如,匿名函数表达式可以存储在变量里,传给另外一个函数,或直接调用

f[0] = function(x) { return x*x; }; // Define a function and store it a.sort(function(a,b){return a-b;}); // Define a function; pass it to another var tensquared = (function(x) {return x*x;})(10); // Define and invoke

 

 

 

3
3
分享到:
评论
1 楼 bigbighead 2010-12-28  
非常感谢你的 JavaScript Definitive Guide

相关推荐

Global site tag (gtag.js) - Google Analytics