我在閱讀「Javascript:The Good Parts」,我完全被這裏發生的事情困惑不解。更詳細和/或簡化的解釋將不勝感激。閉包:逐行解釋「Javascript:Good Parts」的例子?
// BAD EXAMPLE
// Make a function that assigns event handler functions to an array of nodes the wrong way.
// When you click on a node, an alert box is supposed to display the ordinal of the node.
// But it always displays the number of nodes instead.
var add_the_handlers = function (nodes) {
var i;
for (i = 0; i < nodes.length; i += 1) {
nodes[i].onclick = function (e) {
alert(i);
}
}
};
// END BAD EXAMPLE
的add_the_handlers
功能旨在給每個處理器的唯一編號(i)中。因爲處理函數被綁定到變量i
,不是變量i
在功能產生的時間值失敗:
// BETTER EXAMPLE
// Make a function that assigns event handler functions to an array of nodes the right way.
// When you click on a node, an alert box will display the ordinal of the node.
var add_the_handlers = function (nodes) {
var i;
for (i = 0; i < nodes.length; i += 1) {
nodes[i].onclick = function (i) {
return function (e) {
alert(i);
};
}(i);
}
};
現在,而不是到的onclick分配功能,我們定義一個函數,立即調用它,傳入i
。該函數將返回一個事件處理函數,該函數綁定到傳入的i
的值,而不是add_the_handlers
中定義的i
。該返回的函數被分配給onclick。
見標記的問題:http://stackoverflow.com/questions/tagged/javascript+closures+loops – CMS 2010-06-01 06:52:55
你也可以玩現場演示http://jsbin.com/sezisalulede/1/edit?html,js,output – 2014-09-15 18:09:07