我需要从子类更改父类的静态方法。
来自 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes/static我阅读:
Static method calls are made directly on the class and are not callable on instances of the class.
在下面的例子中,我有一个 Parent
类,它有一个 foo()
方法调用 bar()
方法(都是静态的).我需要从 Child
子类更改 bar
以便调用 Child.foo()
将调用修改后的 bar 方法而不是原始方法。
是否有可能(可能是在 Child 的构造函数
中)?
class Parent {
static foo() {
Parent.bar();
}
static bar() {
console.log("HERE I AM");
}
}
class Child extends Parent {
static bar() {
super.bar(); // maybe not what I want?
console.log(", FELLAS!");
}
}
Parent.foo(); // HERE I AM
Child.foo(); // HERE I AM, FELLAS! (need this!)
最佳答案
您的问题是 foo
直接调用 Parent.bar()
,而不是 this.bar()
。通过显式引用 Parent
,它根本不考虑 Child
中的覆盖方法。 Child.bar
怎么写,是否调用super.bar
都没有关系。
class Parent {
static foo() {
this.bar();
// ^^^^
}
static bar() {
return "HERE I AM";
}
}
class Child extends Parent {
static bar() {
return super.bar() + ", FELLAS!";
}
}
console.log(Parent.foo()); // HERE I AM
console.log(Child.foo()); // HERE I AM, FELLAS!
static bar()
方法中的 this
关键字现在引用 Child.foo() 中的
调用,并调用其重写的 Child
类bar
方法。
唯一的选择(如果你不能修改Parent
)是重写foo
方法,复制Parent
代码但是调用Child.bar()
明确存在。
关于javascript - 从子类更改父类的静态方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57245090/