问题
I'm trying to figure out what's going on here, as the Parent/Super class does not have data after the initial construction.
// 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'
Why does class A not keeping state?
回答1:
This is what I found:
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'
}
}
So basically the thing that works is Style3 Style 4 work.
来源:https://stackoverflow.com/questions/44208620/es6-super-class-doesnt-hold-state