JS的继承类和ES6的继承类对比

JS继承类的写法

// 父类
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.playGame = function() {
    
    
	console.log('我能打游戏!!');
}
SmartPhone.prototype.photo = function() {
    
    
	console.log('我能拍照!!');
}

var onePlus = new SmartPhone('一加', 2499, '黑色', '4.4inch');
console.log(onePlus);

在这里插入图片描述

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); // 相当于Phone.call(this, brand, price)
		this.color = color;
		this.size = size;
	}
	photo() {
    
    
		console.log('拍照!!');
	}
	playGame() {
    
    
		console.log('打游戏!!');
	}
}
const ml = new SmartPhone('小米', 1999, '蓝色', '5.0inch');
console.log(ml);

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/weixin_46683645/article/details/118576430