![](/img/trans.png)
[英]Can a instance method in a Javascript subclass call it's parents static method?
[英]How to call a static subclass method in JavaScript
如何从父类的静态方法调用子类的静态方法?
class A {
static foo(){
// call subclass static method bar()
}
}
class B extends A {
static bar(){
// do something
}
}
B.foo()
更新 :
我尝试这个的原因是A的子类在我的上下文中最适合作为单例,我想在A中使用模板方法模式 。
因为看起来我无法从静态上下文中获取对子类的引用,所以我现在正在导出A的子类的实例,它们也可以正常工作。 谢谢。
更新2
是的,它是一个程度的重复(另一个问题不涉及子类)。 即使从静态上下文,引用也是this
。 这样可行:
static foo(){
this.bar();
}
我对你的需求有点困惑,因为你似乎已经得到了你需要用B.foo()做的事情。 那么,这就是你需要的吗?
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?
这是你要问的吗? 如果这不能回答你的问题,请告诉我我的误解,我会尽力回答。 谢谢。
它使模板模式稍微不那么优雅,但你可以通过子类中的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.