【发布时间】: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