javascript - JS : variable inheritance in anonymous functions - scope

标签 javascript scope anonymous-function

长话短说:

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/

相关文章:

javascript - 为什么变量没有被访问

node.js - NodeJS Express app.locals 无法在函数中直接访问

node.js - 变量范围在 Mocha 测试框架中是如何工作的?

javascript - 试图理解 evercookie 中的代码结构

javascript - 在不改变位置的情况下缩放 svg 组

javascript - Google 表格,具有服务帐户的 JWT 客户端

PHP - 检查 $get 变量然后清除 div 并包含 php 文件

javascript - 为什么这段 C 代码在 JavaScript 中不起作用?

swift - 如何声明具有两种可能类型的变量

php - PHP引擎是否优化循环内的匿名函数?