4

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

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. 我不确定发生了什么事。

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

4

4 回答 4

4

这个话题出现了很多,但由于“this”已从 SO 搜索中删除,因此很难搜索。

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

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

obj = function()
{
  var self = this; 
  this.foo = undefined; 
  this.changeState = function()
  {
    self.foo = "bar";
  }
} 
于 2009-09-08T16:39:47.460 回答
3

除非您在调用函数时指定 this 上下文,否则默认值为全局(在浏览器中为 window)。

替代方案是:-

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.
  }; 

};

于 2009-09-08T16:35:58.967 回答
3
function obj() { 
    this.foo = undefined; 
    this.changeState = function () { this.foo = "bar" };
};

var o = new obj();
o.changeState();
alert(o.foo);

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

于 2009-09-08T16:39:18.163 回答
2

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

obj = function() { 
    this.foo = undefined; 
    var self = this; 
    this.changeState = function () { 
        (function () { self.foo = "bar" })();
    }; 
}; 
于 2009-09-08T16:34:01.310 回答