JavaScript 的父類和子類可以使用同名的函式嗎?


是的,父類和子類可以具有同名的函式。

示例

class Parent {
   constructor(parentValue) {
      this.parentValue = parentValue;
   }
   //Parent class method name which is same as Child Class method name.
   showValues() {
      console.log("The parent method is called.....");
      console.log("the value is="+this.parentValue);
   }
}
class Child extends Parent {
   constructor(parentValue,childValue){
      super(parentValue);
      this.childValue = childValue;
   }
   //Child class method name which is same as Parent Class method name.
   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

更新於: 2020 年 9 月 14 日

1 千次以上瀏覽

開啟你的 事業

完成教程,獲取認證

開始
廣告