0

我是 javascript 新手并试图了解此代码的行为,该代码尝试将唯一的 onclick 处理程序分配给数组 myElements[] 中的不同 DOM 元素:

(function handleClicks(){
for (var i = 0; i < 100; ++i) {
myElements[i].onclick = function() {
        alert( 'You clicked on: ' + i );
};
})();

我的理解是,每次单击 DOM 元素时,浏览器都应提醒“您单击了 100”,因为一旦函数完成,javascript 将使用i的值

我有两个问题:

  1. 如果i仅在函数 handleClicks() 中具有作用域,一旦函数完成,浏览器如何访问i - 肯定i不再存在?
  2. 我通过将两个 HTML 元素放入数组中来尝试此代码

var myElements = [];

myElements.push( document.getElementById('1');

myElements.push( document.getElementById('2');

http://jsfiddle.net/bramong/fS7qE/

但是当程序运行时,它会为每个单击的元素提醒“您点击了:2”。

为什么它不提醒“您点击了:100”。因为一旦函数完成运行,这肯定是 i 的值?

4

2 回答 2

1

“如果i只有功能范围内的功能,一旦功能完成handleClicks(),浏览器如何访问- 肯定不再存在?”ii

i变量在封闭范围内(函数handleClicks。当一个函数被创建时,它会在函数的生命周期内携带它的原始变量范围。这称为闭包

Because of this, all the handler functions created in the loop are referencing the same i variable that exists in handleClicks. This keeps i alive. When you destroy the handlers, i will be able to be garbage collected.


The second code example stops at 2 because you get a TypeError for accessing a property on undefined. This halts the execution of the code.

于 2012-07-26T13:48:36.047 回答
0

This is because you have only two elements in the myElements array. So, the loop executes only uptil 2 and errors out after that. If you added 5 elements it would show 5, show 100 if you added 100.

于 2012-07-26T13:48:50.837 回答