Javascript(ES8)-从父类获取类的静态值



我有一个类Parent(使用class声明定义,尽管我知道这主要是语法糖(和多个扩展它的类(Child1Child2等(。子类有一个静态属性分配给它们(在它们的声明之外-据我所知,没有办法在类声明中分配静态属性(。

我想从父类访问任何子类的静态值,例如在方法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的值,但是按照上面所写的方法尝试访问总是返回undefined。换句话说:

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"

有没有一种方法可以从父类访问子类的静态值,而在任何情况下都不必知道子类的名称?

您可以使用类实例的constructor属性来访问作为实例构造函数属性的静态属性,如:

class Parent {
constructor() {
//Do parent stuff
}
getStaticValue() {
return this.constructor.staticValue;
}
}

警告

对象的构造函数属性是从原型链继承的。

类语法使类构造函数的函数对象prototype对象属性不可配置(好(,但使同一原型对象的constructor属性可写(坏(。

NEVER如果您知道什么对您有好处希望类扩展正常工作,请更改类构造函数原型对象的constructor值。

演示:

class Parent {
constructor() {
//Do parent stuff
}
getStaticValue() {
return "The value of staticValue is " + this.constructor.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";
console.log(new Parent().getStaticValue()); 
console.log(new Child1().getStaticValue());
console.log(new Child2().getStaticValue());

您可以使用子类中的super((将静态值传递给父构造函数:

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";

最新更新