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