//A.Using let
var list = document.getElementById('list');
for (let i = 1; i <= 5; i++) {
let item = document.createElement('li');
item.appendChild(document.createTextNode('Item ' + i));
item.onclick = function(ev) {
console.log('Item ' + i + ' is clicked.');
};
list.appendChild(item);
}
//B. Using var
// to achieve the same effect with 'var'
// you have to create a different context
// using a closure to preserve the value
for (var i = 1; i <= 5; i++) {
var item = document.createElement('li');
item.appendChild(document.createTextNode('Item ' + i));
(function(i){
item.onclick = function(ev) {
console.log('Item ' + i + ' is clicked.');
};
})(i);
list.appendChild(item);
}
問題:
正如在B節中,封閉件被用來保存值i
,但其中使用let
不需要在A節封閉。 let
如何幫助保留i
的價值? 謝謝。爲什麼在使用let(ES6)時不需要使用閉包?
*「一個閉包被用來保存'i'的值。」* **否!** *閉包*與*解*無關。重要的部分是你正在執行一個函數(在每次迭代中),從而創建一個新的範圍*(每次迭代)。函數是否是閉包是無關緊要的。 –