我在模块( Node )内有以下设置,但这可以适用于任何地方。
function Storefront(){
this.list = 'List';
}
Storefront.prototype = {
categories : {
get : function(){
return this.list + ' here!';
}
}
}
module.exports = function(){
if(!(this instanceof Storefront)) { return new Storefront(); }
}
稍后,我在另一个模块中将该对象实例化为 sfront
并调用 sfront.categories.get();
。
通常,在函数内执行 var self = this;
,调用其中的子函数,然后引用 self
会很容易。由于显而易见的原因,这不起作用:引用“this”的对象位于另一个对象内部。我不太确定如何将父对象 Storefront 的上下文传递到子对象(类别)的子属性函数“get”中。现在它显示为'undefined'
,这是可以理解的。
最佳答案
您可以将类别
设为属性:
Object.defineProperty(Storefront.prototype, 'categories', {
get: function () {
var storefront = this;
return {
get: function () {
return storefront.list + ' here!';
}
};
}
});
...这是重命名嵌套 get
的一个很好的论据。不过,根据 categories
应该代表什么,将其完全变成不同的类可能更合适:
function StorefrontCategoryList(storefront) {
this.storefront = storefront;
}
StorefrontCategoryList.prototype.get = function () {
return this.storefront.list + ' here!';
};
function Storefront() {
this.list = 'List';
this.categories = new StorefrontCategoryList(this);
}
关于javascript - 当调用 'this' 的函数位于子对象的对象内部时,您将如何引用 'this'?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27559236/