以下示例摘自“Javascript:好的部分”一书。作者说辅助函数返回一个绑定(bind)到 var i
的当前值 的函数。
谁能解释是什么让它绑定(bind)了 var i
的 VALUE 而不是 REFERENCE,因为 helper
函数是 add_the_handler
函数的闭包并且应该只看到 var i
的引用:
var add_the_handlers = function (nodes) {
var helper = function (i) {
return function (e) {
alert(i);
};
};
var i;
for (i = 0; i < nodes.length; i += 1) {
nodes[i].onclick = helper(i);
}
};
最佳答案
如果你要说:
nodes[i].onclick = function(){ alert(i) };
函数不会有它自己的 i
副本,因为 i
没有在函数范围内声明。
为了帮助您更好地理解这一点,我修改了您上面的代码:
var add_the_handlers = function (nodes) {
var helper = function(t) {
// t is in the scope of "helper"
return function(e){
// e is in the scope of this anonymous function
// and is not used
alert(t);
};
};
// Variables declared here are in the scope of "add_the_handlers"
var i;
for (i = 0; i < nodes.length; i += 1) {
nodes[i].onclick = helper(i);
}
};
在“现实世界”中,您经常会看到上面的代码被缩短为如下所示:
var add_the_handlers = function(nodes){
var i;
for(i = 0; i < nodes.length; i++)
nodes[i].onclick = (function(i){ return function(e){ alert(i); }; })(i);
};
关于Javascript 闭包 - 绑定(bind)值而不是引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6728653/