代码之家  ›  专栏  ›  技术社区  ›  nikksan

从静态类访问派生类属性

  •  0
  • nikksan  · 技术社区  · 7 年前

    我有一个我想要访问的示例用例 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 回复  |  直到 7 年前
        1
  •  2
  •   Mark    7 年前

    原型 MyOtherClass 指向 MyClass 所以它应该已经在原型链中,允许您直接访问它。然后使用 this 访问应指向的调用上下文 肌病 既然你要和它打电话 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()
    推荐文章