我正在试图弄清楚这里发生了什么,因为在初始构建之后,Parent / Super类没有数据。
// imports / server / a-and-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'
}
}
// imports / server / 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();
// imports / server / 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班没有保持状态?
答案 0 :(得分:0)
这是我发现的:
class A {
constructor(id) {
// make MongoDB call and store inside this variable
// ...
this._LocalVariable = FieldFromMongo;
}
get LocalVar() {
return this._LocalVariable;
}
GetThatLocalVar() {
return this._LocalVariable;
}
}
export class B extends A {
constructor(id) {
super(id);
}
get Style1() {
// Reference to Parent get function
return super.LocalVar; // => This has a undefined value when called
}
get Style2() {
// Reference to Parent property
return super._LocalVariable; // => This has a undefined value when called
}
get Style3() {
// Reference to local Property that is declared in Parent
return this._LocalVariable; // => This works
}
get Style4() {
// Reference to Parent without the getter
return super.GetThatLocalVar(); // => This works
}
get GETTHEVAR() {
return this.TEST; // => This returns 'THIS IS A TEST'
}
}
所以基本上可行的是Style3 Style 4的工作。