【发布时间】:2016-02-02 20:27:24
【问题描述】:
我正在定义一个 Parent 对象,我希望它有一个子成员对象,该对象拥有自己的函数和私有变量。为了封装函数和变量,我在父原型中添加了一个自执行匿名函数。
这是演示问题的代码:
var Parent = function() {
this.memberVariable = 'hello world';
}
Parent.prototype.doSomething = function() {
return this.childObject.doSomething();
};
Parent.prototype.childObject = function() {
// instead of being Parent, `this` is the Window object. What is the best way to fix this?
var that = this;
return {
doSomething: function() {
// undefined, but should be 'hello world'
return that.memberVariable;
}
}
}();
var parent = new Parent();
console.log(parent.doSomething());
我有一个解决方法是将 Parent 范围传递给子函数,但这看起来很奇怪,而且似乎必须有更好的解决方案:
var Parent = function() {
this.memberVariable = 'hello world';
}
Parent.prototype.doSomething = function() {
// we pass in `this`
return this.childObject.doSomething(this);
};
Parent.prototype.childObject = function() {
return {
doSomething: function(that) {
return that.memberVariable;
}
}
}();
var parent = new Parent();
console.log(parent.doSomething());
有没有更好的方法来做到这一点?
【问题讨论】:
-
你应该看看模块/显示模块模式...addyosmani.com/resources/essentialjsdesignpatterns/book/…
-
你不能有一个 IEFE 来创建一个原型方法并期望在里面得到一个动态的
this。
标签: javascript scope anonymous-function