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
廣告
資料結構
網路技術
資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP