javascript - JavaScript 父类和子类可以有同名的方法吗?
问题描述
以下作品。
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}`;
}
推荐阅读
- python - 如何在 html 中调整表单(relaive auth 表单)
- javascript - 使用 Jquery 不完全正确的两个变化变量的总和
- sql - 检查字符串是否包含任何数值
- laravel - laravel 5.7 获得多对多关系结果的正确方法
- javascript - 在 React 初始化时,props 是未定义的。为什么?
- python - 安装的 lxml 在使用另一个函数时会导致 TypeError
- java - 设置后退图标时如何取回汉堡图标?
- google-chrome - 谷歌奥马哈安装程序挂起
- kubernetes - GKE - 我可以更改 CNI 插件吗?
- matlab - 求解 Ax = b , CUDA vs Matlab