0
我在我的應用程序中有一個主類,並且在它的初始化例程中this.init()
我試圖將其他類的一些其他實例分配給主類但上下文我不知道如何避免這種情況在主類中分配類的實例並保留子類實例的上下文
function Models(settings) {
Object.defineProperty(this, "active", {
configurable: false,
enumerable: false,
writable: true,
value: undefined
});
if (!(this instanceof Models)) {
return new Models(settings);
} else {
return this;
}
}
Object.defineProperties(Models.prototype, {
constructor: Models,
load: {
configurable: false,
enumerable: false,
writable: false,
value: function(id) {
console.log(id, this, typeof id, this.hasOwnProperty(id));
if (typeof id !== typeof undefined && this.hasOwnProperty(id)) {
for (var i = 0, len = this[id].length; i < len; i++) {
this[id][i].emit("show");
}
this.active = id;
}
return this;
}
},
unload: {
configurable: false,
enumerable: false,
writable: false,
value: function(id) {
if (typeof id !== typeof undefined && this.hasOwnProperty(id)) {
for (var i = 0, len = this[id]; i < len; i++) {
this[id][i].emit("hide");
}
}
if (id === this.active) {
this.active = undefined;
}
return this;
}
},
loadOnly: {
configurable: false,
enumerable: false,
writable: false,
value: function(id) {
this.unload(this.active).load(id);
}
}
});
this.models = new Models();
this.on("models.load", this.models.load);
this.on("models.unload", this.models.unload);
this.on("models.loadOnly", this.models.loadOnly);
這是我的init函數中的代碼。問題是,在分配this.models = new Models()
之後,this.models仍在引用主類而不是新創建的Models實例。