在js中,类本质上还是构造构造函数的语法糖,使用的依旧是原型继承,通过下列的步骤可以实现类的效果。
//父类构造函数
function phone(brand, price) {
this.brand = brand
this.price = price
}
//父类的方法
phone.prototype.phoneCall = function () {
console.log('我可以打电话')
}
//子类的构造函数
function smartPhone(brand, price, network, video) {
phone.call(this, brand, price)
this.network = network
this.video = video
}
//子类的原型指向父类的实例,这里使用Object创建一个指向父类原型的空对象
smartPhone.prototype = Object.create(phone.prototype)
//constructor指向子类构造函数
smartPhone.prototype.constructor = smartPhone
smartPhone.prototype.picture = function () {
console.log('我可以拍照')
}
打印结果: