首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Javascript (ES8) -从父类获取类的静态值

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

Stack Overflow用户
提问于 2018-12-01 20:56:11
回答 1查看 880关注 0票数 2

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

我想从父类访问任何子类的静态值,比如在方法getStaticValue()中。

代码语言:javascript
复制
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值,但是尝试像上面写的那样做时总是返回未定义的。换言之:

代码语言:javascript
复制
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"

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

EN

回答 1

Stack Overflow用户

发布于 2018-12-01 21:03:52

可以在子类中使用超级()将静态值传递给父构造函数:

代码语言:javascript
复制
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";
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/53574965

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档