[英]How to call a static subclass method in JavaScript
How can I call a static method of a subclass from a static method of the parent class? 如何从父类的静态方法调用子类的静态方法?
class A {
static foo(){
// call subclass static method bar()
}
}
class B extends A {
static bar(){
// do something
}
}
B.foo()
Update : 更新 :
The reason why I tried this is that subclasses of A would have worked best as singletons in my context and I wanted to use the template method pattern in A. 我尝试这个的原因是A的子类在我的上下文中最适合作为单例,我想在A中使用模板方法模式 。
Since it looks like I cannot get a reference to a subclass from a static context I am now exporting instances of subclasses of A which works just as well. 因为看起来我无法从静态上下文中获取对子类的引用,所以我现在正在导出A的子类的实例,它们也可以正常工作。 Thanks. 谢谢。
Update 2 更新2
Yes, it is a duplicate to a degree (the other question does not involve subclassing). 是的,它是一个程度的重复(另一个问题不涉及子类)。 The reference, even from a static context, is this
. 即使从静态上下文,引用也是this
。 So this works: 这样可行:
static foo(){
this.bar();
}
I am a bit confused to your need, as it seems you sorta already get what you need to do with B.foo(). 我对你的需求有点困惑,因为你似乎已经得到了你需要用B.foo()做的事情。 So, is this what you need? 那么,这就是你需要的吗?
class A {
static foo(){
// call subclass static method bar()
// Because it is "static" you reference it by just calling it via
// the class w/o instantiating it.
B.bar()
}
}
class B extends A {
static bar(){
// do something
console.log("I am a static method being called")
}
}
// because "foo" is static you can call it directly off of
// the class, like you are doing
B.foo()
// or
var D = new B()
D.bar() // won't work ERROR
A.foo() // Works <-- Is this is specifically what you are asking? Or
// calling it in the Super class like B.bar(), that is done in static method foo?
Is this what you are asking? 这是你要问的吗? If this does not answer your question, please let me know what I am misunderstanding and I'll try to answer. 如果这不能回答你的问题,请告诉我我的误解,我会尽力回答。 Thanks. 谢谢。
It makes the template pattern somewhat less elegant, but you can accomplish this via super
in the subclass, eg: 它使模板模式稍微不那么优雅,但你可以通过子类中的super
来实现这一点,例如:
class A {
static foo() {
this.bar()
}
}
class B extends A {
static foo() {
super.foo()
}
static bar() {
console.log("Hello from B")
}
}
B.foo()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.