我有一个类Parent (使用class声明定义,但我知道这主要是语法糖),以及扩展它的多个类(Child1、Child2等)。子类有一个分配给它们的静态属性(除了它们的声明之外--据我所知,没有办法在类声明中分配静态属性)。
我想从父类访问任何子类的静态值,比如在方法getStaticValue()中。
class Parent {
constructor() {
//Do parent stuff
}
getStaticValue() {
return "The value of staticValue is " + this.staticValue;
}
}
class Child1 extends Parent {
constructor() {
super();
//Do child1 stuff
}
}
Child1.staticValue = "Child1";
class Child2 extends Parent {
constructor() {
super();
//Do child2 stuff
}
}
Child2.staticValue = "Child2";我想从父类中访问任意子类的staticValue值,但是尝试像上面写的那样做时总是返回未定义的。换言之:
let parentStaticValue = new Parent().getStaticValue();
//Desired output = "The value of staticValue is undefined"
//Actual output = "The value of staticValue is undefined"
let child1StaticValue = new Child1().getStaticValue();
//Desired output = "The value of staticValue is Child1"
//Actual output = "The value of staticValue is undefined"
let child2StaticValue = new Child2().getStaticValue();
//Desired output = "The value of staticValue is Child2"
//Actual output = "The value of staticValue is undefined"是否有一种方法可以从父类访问子类的静态值,而不必在每种情况下都知道子类的名称?
发布于 2018-12-01 21:03:52
可以在子类中使用超级()将静态值传递给父构造函数:
class Parent {
constructor(childStaticValue) { // receive the value from the children class
this.staticValue = childStaticValue // and assign it to the local variable
}
getStaticValue() {
return "The value of staticValue is " + this.staticValue;
}
}
class Child1 extends Parent {
constructor() {
super(Child1.staticValue); // pass the value to the parent class
//Do child1 stuff
}
}
Child1.staticValue = "Child1";
class Child2 extends Parent {
constructor() {
super(Child2.staticValue); // pass the value to the parent class
//Do child2 stuff
}
}
Child2.staticValue = "Child2";https://stackoverflow.com/questions/53574965
复制相似问题