js es5构造函数继承和es6类继承
es5构造函数继承
function Phone(brand, price){ this.brand = brand; this.price = price; } Phone.prototype.call = function(){ console.log("打电话"); } function SmartPhone(brand, price, color, size){ Phone.call(this, brand, price); this.color = color; this.size = size; } // 设置子级构造函数的原型 SmartPhone.prototype = new Phone; SmartPhone.prototype.constructor = SmartPhone;//校正 // 声明子类的方法 SmartPhone.prototype.photo = function(){ console.log("拍照"); } SmartPhone.prototype.playGame = function(){ console.log("玩游戏"); } const Huawei = new SmartPhone("华为",5499,"黑色","5.5inch"); console.log(Huawei);
es6类继承
class Phone{ // 构造方法 constructor(brand, price){ this.brand = brand; this.price = price; } call(){ console.log("打电话"); } } class SmartPhone extends Phone { // 构造方法 constructor(brand, price, color, size){ super(brand,price); this.color = color; this.size = size; } photo(){ console.log("拍照"); } playGame(){ console.log("玩游戏"); } // 重写父类方法 call(){ console.log("视频通话"); } } const Huawei = new SmartPhone("华为",5499,"黑色","5.5inch") console.log(Huawei) Huawei.call(); Huawei.photo(); Huawei.playGame();