我有这个示例用例,我想从派生类的静态方法中访问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
的原型(prototype)指向 MyClass
,因此它应该已经在原型(prototype)链中,允许您直接访问它。然后使用 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()
关于javascript - 从静态类访问派生类属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51389576/