【问题标题】:Reference Instance Variables in Javascript Constructor在 Javascript 构造函数中引用实例变量
【发布时间】:2010-11-26 13:35:36
【问题描述】:

我正在尝试通过执行以下操作来维护对象的状态:

obj = function() { 
    this.foo = undefined; 
    this.changeState = function () { 
        (function () { this.foo = "bar" })(); // This is contrived, but same idea.
    }; 
};

我想在调用 changeState 方法时将实例变量 foo 设置为“bar”。

例如:

o = new obj();
o.changeState();
alert(o.foo); // This should say "bar"

据我所知,正在发生的事情是内部匿名函数中的“this”指向 window.我不确定发生了什么。

我在正确的轨道上吗?有更好的方法吗?

【问题讨论】:

    标签: javascript oop closures anonymous-function


    【解决方案1】:

    这个话题经常出现,但很难搜索,因为“this”已从 SO 搜索中删除。

    基本上,在 JavaScript 中,this 总是指调用对象,而不是上下文对象。由于这里我们从全局范围调用 o.changeState(),this 指的是窗口。

    在这种情况下,您实际上不需要内部函数来使闭包起作用 - changeState 函数本身就足以关闭词法范围。

    obj = function()
    {
      var self = this; 
      this.foo = undefined; 
      this.changeState = function()
      {
        self.foo = "bar";
      }
    } 
    

    【讨论】:

      【解决方案2】:

      除非您在调用函数时指定 this 上下文,否则默认将是全局的(在浏览器中是窗口)。

      替代方案是:-

      obj = function() { 
        this.foo = undefined; 
        this.changeState = function () { 
          (function () { this.foo = "bar" }).call(this); // This is contrived, but same idea.
        }; 
      

      };

      或:-

      obj = function() {
        var self = this;
        this.foo = undefined; 
        this.changeState = function () { 
          (function () { self.foo = "bar" })(); // This is contrived, but same idea.
        }; 
      

      };

      【讨论】:

        【解决方案3】:
        function obj() { 
            this.foo = undefined; 
            this.changeState = function () { this.foo = "bar" };
        };
        
        var o = new obj();
        o.changeState();
        alert(o.foo);
        

        为我工作。我不确定您为什么要使用自调用函数来分配函数引用,也不确定为什么要为构造函数使用函数表达式而不是函数声明。

        【讨论】:

          【解决方案4】:

          我想通了。只需要保存对当前上下文的引用并在内部匿名函数中使用它:

          obj = function() { 
              this.foo = undefined; 
              var self = this; 
              this.changeState = function () { 
                  (function () { self.foo = "bar" })();
              }; 
          }; 
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2014-01-12
            • 2023-03-02
            • 1970-01-01
            • 1970-01-01
            • 2016-11-02
            • 2017-05-30
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多