fho*_*zer 4 javascript scope anonymous-function
嘿伙计们,来自doctype的人把我送到了这里.
长话短说:
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
Run Code Online (Sandbox Code Playgroud)
实际上我的代码有点复杂.
我的脚本遍历许多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"
Run Code Online (Sandbox Code Playgroud)
有关更详细的描述,请参阅MDC文章,其中有一节介绍如何使用带循环的闭包.
这种技术可以在你的循环中应用.这样的事情是你想要做的:
var fn = function(x, y) {
return function() {
rr_download_start(x, y);
}
} (i, this);
link.addEventListener('click', fn ,false);
Run Code Online (Sandbox Code Playgroud)
您可以尝试使用这样的自调用函数:
var o = 0;
for(var i=0;i<elements.length;i++){
(function(obj,variable){
obj.onclick = function(){
alert(variable);
}
})(elements[i],o);
o++;
}
Run Code Online (Sandbox Code Playgroud)
这应该警告"o"处于循环期间的任何值,而不是警告"o"的最终值.
我希望这在某种程度上有所帮助.
| 归档时间: |
|
| 查看次数: |
3182 次 |
| 最近记录: |