我想弄清楚這裏發生了什麼,因爲父類/超類在初始構建後沒有數據。ES6:超級類不保持狀態
//進口/服務器/一 - 和 - b.js
class A {
constructor(id) {
// make MongoDB call and store inside this variable
// ...
this._LocalVariable = FieldFromMongo;
console.log(`this._LocalVariable: ${this._LocalVariable}`); // => This has a good value, ie: 'Test'
}
get LocalVar() {
console.log(`this._LocalVariable: ${this._LocalVariable}`); // => This has a undefined value when called from child class
return this._LocalVariable;
}
}
export class B extends A {
constructor(id) {
super(id);
this.TEST = 'THIS IS A TEST';
}
get THE_Variable() {
console.log(`super.LocalVar: ${super.LocalVar}`); // => This has a undefined value when called
return super.LocalVar;
}
get GETTHEVAR() {
return this.TEST; // => This returns 'THIS IS A TEST'
}
}
//進口/服務器/ factory.js
import { B } from 'imports/server/a-and-b.js';
class Factory {
constructor() {
this._factory = new Map();
}
BuildInstances(id, cls) {
let instance = this._factory.get(cls);
if (!instance) {
if (cls === 'B') {
instance = new B(id);
this._factory.set(cls, instance);
return instance;
}
}
else {
return instance;
}
}
}
export let OptsFactory = new Factory();
//進口/服務器/ test.js
import { OptsFactory } from 'imports/server/factory.js'
const B = OptsFactory.BuildInstances(id, 'B');
const THE_Variable = B.THE_Variable; // => always undefined
const TEST = B.GETTHEVAR; // => Always returns 'THIS IS A TEST'
爲什麼A類不能保持狀態?
聽起來像你的MongoDB調用是異步的,你期望得到一個同步值。你能否提供一些示例代碼來說明你如何從數據庫中獲得價值? –
這個值實際上是從Mongo返回的,我在console.log中看到它,在上面的代碼中,它是這一行:console.log('this._LocalVariable:$ {this._LocalVariable}'); // =>這有一個很好的價值,即:'測試'。只有當我從Child類中調用它時,它纔是未定義的 - 就像它從未設置它自己的狀態或像Child類沒有保留適當的引用一樣? – Aaron
真的很難遵循這個問題,特別是使用類似名稱的僞代碼並且沒有真正的實際功能。你不用'super.XXX'來訪問實例數據。你使用'this.XXX'。只有一個對象,一個'this'指針和類的所有部分(基類和派生類)都訪問相同的對象和相同的'this'指針。因此,無論基類或派生類的哪一部分創建它或設置它,this.XXX都會訪問一個屬性。 – jfriend00