javascript - NodeJS:从父级访问子级的静态方法
问题描述
我正在使用 ES6:
class Parent {
static sayHello(){
ChildN.sayHi()
}
}
class ChildOne extends Parent {
static sayHi(){
console.log('hi from ChildOne')
}
}
class ChildTwo extends Parent {
static sayHi(){
console.log('hi from ChildTwo')
}
}
ChildOne.sayHello()
ChildTwo.sayHello()
我想要N个孩子。是否可以在父类中动态获取子类并调用其静态方法?换句话说,如何在父类中概括 ChildN?
解决方案
通过访问this
父类的静态方法,您将引用子类,所以只需this.sayHi()
:
class Parent {
static sayHello(){
this.sayHi()
}
}
class ChildOne extends Parent {
static sayHi(){
console.log('hi from ChildOne')
}
}
class ChildTwo extends Parent {
static sayHi(){
console.log('hi from ChildTwo')
}
}
ChildOne.sayHello()
ChildTwo.sayHello()