从静态类访问派生类属性

时间:2018-07-17 20:18:12

标签: javascript static

我有一个示例用例,我想从派生类的静态方法中访问MyOtherClass.property1,但是假设我不知道派生类的名称,我只知道它具有这个特殊的属性。

对于使用new关键字调用的标准类实例,我可以使用new.target

有某种等同于静态的东西吗?

class MyClass{
    static method1(){
        // I want to access MyOtherClass.property1 here 
    }
}

class MyOtherClass extends MyClass{
    static method2(){

    }
}

MyOtherClass.property1 = 1;
MyOtherClass.method1();

1 个答案:

答案 0 :(得分:2)

MyOtherClass的原型指向MyClass,因此它应该已经在原型链中,允许您直接访问它。然后使用this访问调用上下文,该上下文应指向MyOtherClass,因为您正在使用MyOtherClass.method1()进行调用:

class MyClass{
    static method1(){
        console.log("method1", this.property1) 
    }
}

class MyOtherClass extends MyClass{
    static method2(){
        console.log(method2)
    }

}
MyOtherClass.property1 = 1;
MyOtherClass.method1()

相关问题