以下工作原理。
class Parent {
constructor(x) {
this.x = x;
}
present() {
return `I have a ${this.x}`;
}
}
class Child extends Parent {
constructor(x, y) {
super(x);
this.y = y;
}
// different name !!!
show() {
return `${this.present()}, it is a ${this.y}`;
}
}
child = new Child("Tinggu", "Winggu");
console.log(child.present());
然而,与Java不同的是,Parent和Child类中具有相同名称的方法似乎不起作用。
...
class Child extends Parent {
constructor(x, y) {
super(x);
this.y = y;
}
// same name !!!
present() {
return `${this.present()}, it is a ${this.y}`;
}
}
...
有没有办法让它发挥作用?
要调用同名父级的方法,请使用super
:
present() {
return `${super.present()}, it is a ${this.y}`;
}