长话短说:
var o="before";
x = function() //this needs to be an anonymous function
{
alert(o); //the variable "o" is from the parent scope
};
o="after"; //this chages "o" in the anonymous function
x();
//this results in in alert("after");
//which is not the way i want/need it
实际上我的代码要复杂一些。
我的脚本遍历许多 html 对象并为每个元素添加一个事件监听器。
我通过为每个元素声明一个匿名函数并使用 ID 作为参数调用另一个函数来实现这一点。在此示例中,该 ID 由“o”变量表示。
经过一番思考,我明白了为什么会这样,但是有没有办法让 js 在我声明匿名函数时评估 o 而无需处理 id 属性并从那里获取我的 ID?
我的完整源代码在这里:http://pastebin.com/GMieerdw
匿名函数在第 303 行。
最佳答案
您需要为变量o
创建一个闭包。您可以通过分配一个接受值的函数返回一个使用该值的函数来做到这一点。您的示例可以这样修改以获得所需的效果:
var o="before";
x = function(inner) {
return function()
{
alert(inner);
}
} (o); //here, the anonymous function is called, which will return another function which uses o
o="after";
x();//prints "before"
有关更详细的说明,请参阅 the MDC article ,其中有一节是关于在循环中使用闭包的。
可以在您的循环中应用相同的技术。像这样的事情就是你想要做的:
var fn = function(x, y) {
return function() {
rr_download_start(x, y);
}
} (i, this);
link.addEventListener('click', fn ,false);
关于javascript - JS : variable inheritance in anonymous functions - scope,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2806666/