Quoting myself for an explanation of the first example:
(引用我自己来解释第一个示例:)
JavaScript's scopes are function-level, not block-level, and creating a closure just means that the enclosing scope gets added to the lexical environment of the enclosed function.
(JavaScript的作用域是函数级的,而不是块级的,创建闭包只是意味着将封闭的作用域添加到封闭函数的词法环境中。)
After the loop terminates, the function-level variable i has the value 5, and that's what the inner function 'sees'.
(循环终止后,函数级变量i的值为5,这就是内部函数所看到的。)
In the second example, for each iteration step the outer function literal will evaluate to a new function object with its own scope and local variable num
, whose value is set to the current value of i
.
(在第二个示例中,对于每个迭代步骤,外部函数文字将评估为具有自己的作用域和局部变量num
的新函数对象,其值设置为i
的当前值。)
As num
is never modified, it will stay constant over the lifetime of the closure: The next iteration step doesn't overwrite the old value as the function objects are independant.(由于num
从未修改,因此它将在闭包的整个生命周期内保持不变:由于函数对象是独立的,因此下一个迭代步骤不会覆盖旧值。)
Keep in mind that this approach is rather inefficient as two new function objects have to be created for each link.
(请记住,这种方法效率很低,因为必须为每个链接创建两个新的功能对象。)
This is unnecessary, as they can easily be shared if you use the DOM node for information storage:(这是不必要的,因为如果您使用DOM节点进行信息存储,则可以轻松共享它们:)
function linkListener() {
alert(this.i);
}
function addLinks () {
for(var i = 0; i < 5; ++i) {
var link = document.createElement('a');
link.appendChild(document.createTextNode('Link ' + i));
link.i = i;
link.onclick = linkListener;
document.body.appendChild(link);
}
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…