1. 函数定义方法:
1.1 具名函数:
1.1.1 function 函数名(参数列表){函数体;}
如:
function foo(p){alert(p);}
1.1.2 var 函数名 = function(参数列表){函数体;}
如:
var bar = function(p){alert(p);}
1.1.3 var baz = new Function(“x”, “y”, “return x*y;”);
Function
对象是JavaScript里面的固有对象,所有的函数实际上都是一个Function对象。
1.2 匿名函数:
function(参数列表){函数体;}
如:
function(p){alert(p);} //因为是匿名函数,所以一般也不会有参数传递给它。
匿名函数主要有两种常用的场景,一是回调函数,如ajax请求,二是直接执行函数。
2. 函数调用方法:
2.1 具名函数调用:
函数名(参数列表);
如:
foo("a"); bar("b"); baz(2, 3);
2.2 匿名函数调用:
2.1 设定DOM元素事件处理函数时,赋予它的对应事件引用一个匿名函数。
2.2 jQuery片段——使用()
将匿名函数括起来,然后后面再加一对小括号(包含参数列表)。
如
(function(p){alert(p);})(2);
其中 function(p){alert(p);}
是匿名函数, 被一对小括号()括了起来,后面又加了一个小括号(),并且里面传了一个参数2
。
关于小括号():
()
组合表达式运算符,()
里面是一个表达式,表达式用()
括起来后,会有一个表达式的返回值。所以,当用一对()
把匿名函数括起来的时候,实际上()
返回的就是一个匿名函数的Function
对象。
因此,()
括起匿名函数就如同有名字的函数般被我们取得了它的引用位置了。所以在这个引用变量后面再加上(参数列表)
,就会实现普通函数的调用形式。
3. 闭包:
A closure is the combination of a function bundled together (enclosed) with references to its surrounding state (the lexical environment). In other words, a closure gives you access to an outer function’s scope from an inner function. In JavaScript, closures are created every time a function is created, at function creation time.
翻译:
函数与对其状态即词法环境(lexical environment
)的引用共同构成闭包(closure
)。也就是说,闭包可以让你从内部函数访问外部函数的作用域。在JavaScript中,函数在每次创建时生成闭包。
待续。。。