盗用构造函数: 在子类构造函数中调用父类构造函数
// 通过call()或者aplly(),在子类的构造函数中执行父类构造函数
function father() {
this.color = ['red','green']
}
function son() {
father.call(this)
}
let son1 = new son()
son1.color.push('blue')
let son2 = new son()
console.log(son1.color) // ['red','green','blue']
console.log(son2.color) // ['red','green']
等于在子类构造函数里面运行了父类构造函数的初始化代码,结果就是每个子类的实例都有自己的color属性.
传递参数
因为是通过call或者apply去调用,所以就可以给父类构造函数中传入参数
function father(color) {
this.color= color
}
function son() {
father.call(this,'red')
this.name='燕青'
}
let son1 = new son()
console.log(son1.color) // 'red'
console.log(son1.name) // '燕青'
如果要在子类中定义或者覆盖新的属性,需要在调用父类构造函数之后进行,否则会被覆盖掉.
缺点和问题
函数没有复用,每次生成新的实例,都得调用父类构造函数.
因为只是调用了构造函数,所以原型上的东西就都丢失了,子类无法访问父类原型.