[英]Access Derived Class Property from static class
I have this example use-case where I want to access MyOtherClass.property1
from within a static method of the derived class, but assuming I don't know the derived class name, I only know that it has this particular property. 我有一个示例用例,我想从派生类的静态方法中访问MyOtherClass.property1
,但是假设我不知道派生类的名称,我只知道它具有此特定属性。
For a standard class instance invoked with new
keyword I am able to use new.target
. 对于使用new
关键字调用的标准类实例,我可以使用new.target
。
Is there some sort of an equivalent for static? 有某种等效的静态方法吗?
class MyClass{
static method1(){
// I want to access MyOtherClass.property1 here
}
}
class MyOtherClass extends MyClass{
static method2(){
}
}
MyOtherClass.property1 = 1;
MyOtherClass.method1();
The prototype of MyOtherClass
points to MyClass
so it should already be in the prototype chain allowing you to access it directly. MyOtherClass
的原型指向MyClass
因此它应该已经在原型链中,允许您直接访问它。 Then use this
to access the calling context which should point to MyOtherClass
since you are calling it with MyOtherClass.method1()
: 然后使用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.