原型链
父类的引用类型数据会被实例共享
子类无法传递参数给父类构造函数传递参数
function Father () {
this.property = {
name: 'wuxy'
}
}
Father.prototype.getFatherValue = function () {
return this.property
}
function Son () {
this.sonProperty = 32
}
Son.prototype = new Father()
Son.prototype.getChildValue = function () {
return this.sonProperty
}
const son = new Son()
son.property.name = 'wuwu'
const son1 = new Son()
son1.property.name = 'hahah'
console.log(son.property, son1.property) // { name: 'hahah' } { name: 'hahah' }
console.log(son.getFatherValue(), son.getChildValue()) // { name: 'hahah' } 32
构造函数继承
父类引用属性 不在所有实例共享
无法继承父类的方法,失去了继承的意义
function Father (property) {
this.colors = ['pink', 'green', 'blue']
this.property = property
}
Father.prototype.getColors = function () {
console.log(this.colors.toString())
}
function Son (property) {
Father.call(this, property)
}
const son = new Son(212)
const son2 = new Son(111)
son2.colors.push('yellow')
console.log(son.colors, son.property) // [ 'pink', 'green', 'blue' ] 212
console.log(son2.colors, son2.property) // [ 'pink', 'green', 'blue', 'yellow' ] 111
console.log(son.getColors()) // 报错,getColors is not a function
组合继承 父类引用属性 不共享继承父类方法
function Father () {
this.fatherValue = 11
}
Father.prototype.getFatherValue = function () {
return this.fatherValue
}
function Son () {
Father.call(this) // 继承父类属性
}
Son.prototype = new Father() // 继承父类方法
const son = new Son()
console.log(son.fatherValue, son.getFatherValue())// 11 11