繁体   English   中英

从静态类访问派生类属性

[英]Access Derived Class Property from static class

我有一个示例用例,我想从派生类的静态方法中访问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();

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() 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM