JavaScript父类和子类可以有一个同名的方法吗?
下面的工作JavaScript父类和子类可以有一个同名的方法吗?,javascript,inheritance,ecmascript-6,Javascript,Inheritance,Ecmascript 6,下面的工作 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
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不同,具有相同名称的父类和子类中的方法似乎不起作用
...
class Child extends Parent {
constructor(x, y) {
super(x);
this.y = y;
}
// same name !!!
present() {
return `${this.present()}, it is a ${this.y}`;
}
}
...
是否还有其他方法可以实现此功能?要调用同名父级的方法,请使用:
要使用相同名称调用父级的方法,请使用:
啊。愚蠢的错误!明白了,谢谢。但是在这种情况下,从子对象调用父方法的方法是什么<代码>子代=新子代(“庭谷”、“翼谷”);console.log(child.present());//这是不可能的,这可能是一件好事。使用
Child
的代码不应该对其实现进行任何假设。实际上。。。这是可能的。我在这里发现的。我是说。。。当然您还可以执行Object.getPrototypeOf(Object.getPrototpyeOf(child)).present.call(child)
。但这两种方法都不能改变调用者现在对child
的实现做出假设的事实,这并不好。如果您认为必须这样做,那么可能值得后退一步并更改类的体系结构/组成。Aaah。愚蠢的错误!明白了,谢谢。但是在这种情况下,从子对象调用父方法的方法是什么<代码>子代=新子代(“庭谷”、“翼谷”);console.log(child.present());//这是不可能的,这可能是一件好事。使用Child
的代码不应该对其实现进行任何假设。实际上。。。这是可能的。我在这里发现的。我是说。。。当然您还可以执行Object.getPrototypeOf(Object.getPrototpyeOf(child)).present.call(child)
。但这两种方法都不能改变调用者现在对child
的实现做出假设的事实,这并不好。如果您认为必须这样做,那么就值得后退一步,更改类的体系结构/组成。
present() {
return `${super.present()}, it is a ${this.y}`;
}