JavaScript 父类和子类可以有同名的方法吗?

javascriptweb developmentobject oriented programming更新于 2025/11/21 23:40:17

是的,父类和子类可以有同名的方法。

示例

class Parent {
   constructor(parentValue) {
      this.parentValue = parentValue;
   }
   //父类方法名与子类方法名相同。
   showValues() {
      console.log("调用父类方法.....");
      console.log("the value is="+this.parentValue);
   }
}
class Child extends Parent {
   constructor(parentValue,childValue){
      super(parentValue);
      this.childValue = childValue;
   }
   //子类方法名与父类方法名相同。
   showValues() {
      console.log("The child method is called.....");
      console.log("The value is="+`${this.childValue}`);
   }
}
var parentObject = new Parent(100);
parentObject.showValues();
var childObject = new Child(400,500);
childObject.showValues();

要运行上述程序,您需要使用以下命令 −

node fileName.js.

这里,文件名是 demo195.js。

输出

这将产生以下输出 −

PS C:\Users\Amit\javascript-code> node demo195.js
The parent method is called.....
the value is=100
The child method is called.....
The value is=500

相关文章


有用资源