示例
class Electronics {
constructor(name, price) {
this.name = name;
this.price = price;
}
getDescription() {
return `This ${this.name} costs $${this.price}.`;
}
}
class Laptop extends Electronics {
constructor(name, price, screenSize) {
super(name, price);
this.screenSize = screenSize;
}
getDescription() {
return `${super.getDescription()} It has a ${this.screenSize}-inch screen.`;
}
}
class Smartphone extends Electronics {
constructor(name, price, brand) {
super(name, price);
this.brand = brand;
}
getDescription() {
return `${super.getDescription()} It is made by ${this.brand}.`;
}
}
// 创建一个Laptop实例
const myLaptop = new Laptop('MacBook Pro', 1999, 16);
console.log(myLaptop.getDescription());
// 创建一个Smartphone实例
const myPhone = new Smartphone('iPhone 13', 999, 'Apple');
console.log(myPhone.getDescription());
继承父类中 super的 作用
1.初始化父类中的构造方法
2.可以使用super关键字调用父类中的构造方法
如果子类定义了构造函数,则它必须在构造函数中调用super(),以便初始化父类的属性。否则,会导致错误。这种机制确保了继承链上所有相关类的构造函数都能正确执行,从而保证了对象的正确初始化和整个继承链的正确性