我用 babel 对象做了一个简单的例子来说明我的问题:
function babel(){
this.english = {
hello: function () { alert('hello'); },
goodbye: function () { alert('goodbye'); }
teeshirt: function () { alert('T-shirt'); }
}
}
现在,我想扩展这个对象:
babel.prototype.french = {
bonjour: function () { alert('bonjour'); },
aurevoir: function () { alert('au revoir'); }
}
但是如果我需要使用之前定义的现有函数怎么办?
babel.prototype.french = {
bonjour: function () { alert('bonjour'); },
aurevoir: function () { alert('aurevoir'); },
teeshirt: function () { this.english.teeshirt(); }
}
我能做的是:
var say = new babel();
(function (_this) {
babel.prototype.french = {
bonjour: function () { alert('bonjour'); },
aurevoir: function () { alert('aurevoir'); },
hello: function () { _this.english.hello(); }
}
})(say);
但在这种情况下,我将始终使用 say 对象的上下文,不是吗?
最佳答案
问题是,在 teeshirt 函数中调用 this 指向的是 french 对象,而不是 babel 对象。如果你必须访问父对象,你应该在某处存储对它的引用。例如,您可以像这样更改您的构造函数:
function babel(){
this.english = {
parent: this,
hello: function () { alert('hello'); },
goodbye: function () { alert('goodbye'); }
teeshirt: function () { this.parent.french.something(); }
}
}
但是如您所见,如果您不在构造函数中创建对象,就会出现问题。我没有看到任何“好的”方法,但你可以这样做:
function babel(){
this.english = {
parent: this,
hello: function () { alert('hello'); },
goodbye: function () { alert('goodbye'); }
teeshirt: function () { this.parent.french.something(); }
};
for (var i in babel.prototype) {
this[i].parent = this;
}
}
然后你的法语看起来像这样:
babel.prototype.french = {
bonjour: function () { alert('bonjour'); },
aurevoir: function () { alert('aurevoir'); },
teeshirt: function () { this.parent.english.teeshirt(); }
}
关于javascript - 如何扩展一个javascript对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8374046/