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

时间:2018-12-01 20:56:12

标签: javascript javascript-objects

我有一个类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的值,但是,如上文所述,尝试这样做总是返回未定义的。换句话说:

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"

是否有一种方法可以从父类访问子类的静态值,而不必每次都知道子类的名称?

2 个答案:

答案 0 :(得分:2)

您可以在子类中使用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";

答案 1 :(得分:1)

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

class Parent {
    constructor() {
        //Do parent stuff
    }

    getStaticValue() {
        return this.constructor.staticValue;
    }
}

警告

对象的构造方法属性是从原型链继承的。

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

从不更改类构造函数原型对象的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());