【问题标题】:Access Derived Class Property from static class从静态类访问派生类属性
【发布时间】:2018-07-17 20:18:12
【问题描述】:

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

【问题讨论】:

  • 这真的没有意义。 MyClass 中的方法不应假定它只会在子类中调用。你希望MyClass.method1() 做什么?

标签: javascript static


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-16
    相关资源
    最近更新 更多