js继承共享方法

示例

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(),以便初始化父类的属性。否则,会导致错误。这种机制确保了继承链上所有相关类的构造函数都能正确执行,从而保证了对象的正确初始化和整个继承链的正确性

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值