闭包
Prev Chapter 2. JavaScript 基础 Next

闭包

闭包是作用域概念的一个扩展 — 函数能访问函数创建时作用域的变量functions have access to variables that were available in the scope where the function was created. 如果这很困惑,不要担心:通过例子你能更好的理解闭包。

在 Example 2.44, “函数定义后可看见变量值的改变” 我们了解到函数是如何访问到改变的变量值we saw how functions have access to changing variable values. 这种行为同样存在于循环的函数定义中 -- The same sort of behavior exists with functions defined within loops -- 函数观察到变量在函数定义后的改变,产生5次点击警告。the function "sees" the change in the variable's value even after the function is defined, resulting in all clicks alerting 5.

Example 2.46. 如何锁定i的值?

/* this won't behave as we want it to; */
/* every click will alert 5 */
for (var i=0; i<5; i++) {
    $('<p>click me</p>').appendTo('body').click(function() {
        alert(i);
    });
}

Example 2.47. 以一个闭包的方式锁定i的值

/* fix: “close” the value of i inside createFunction, so it won't change */
var createFunction = function(i) {
    return function() { alert(i); };
};

for (var i=0; i<5; i++) {
    $('<p>click me</p>').appendTo('body').click(createFunction(i));
}


Copyright Rebecca Murphey, released under the Creative Commons Attribution-Share Alike 3.0 United States license.


Prev Up Next
作用域 Home Part II. jQuery: 基础概念