Open DamomHd opened 3 years ago
通过原型链
function Parent1(){
this.info = [1,2,3]
this.name = 'parent1'
}
function Child1(){
this.type = 'child1'
}
Child1.prototype = new Parent1()
console.log(new Child1())
通过原型链和call
function Parent1(){
this.info = [1,2,3]
this.name = 'parent1'
}
function Child1(){
Parent1.call(this)
this.type = 'child1'
}
Child1.prototype = new Parent1()
console.log(new Child1())
组合继承优化1
function Parent1(){
this.info = [1,2,3]
this.name = 'parent1'
}
function Child1(){
Parent1.call(this)
this.type = 'child1'
}
Child1.prototype = Parent1.prototype
最佳推荐使用,寄生组合继承
function Parent1(){
this.info = [1,2,3]
this.name = 'parent1'
}
function Child1(){
Parent1.call(this)
this.type = 'child1'
}
Child1.prototype = Object.create(Parent1.prototype)
Child1.prototype.constructor = Child1
通过call实现
function Parent1(){ this.name = 'parent1' } function Child1(){ Parent1.call(this) this.type = 'child1' } console.log(new Child1)
问题:子类能够拿到父类属性值,父类原型对象一旦存在方法则子类无法继承
通过原型链
function Parent1(){ this.info = [1,2,3] this.name = 'parent1' } function Child1(){ this.type = 'child1' } Child1.prototype = new Parent1() console.log(new Child1())
问题:两个实例使用同一个原型对象,改变属性多个实例也会改变
通过原型链和call
function Parent1(){ this.info = [1,2,3] this.name = 'parent1' } function Child1(){ Parent1.call(this) this.type = 'child1' } Child1.prototype = new Parent1() console.log(new Child1())
问题:Parent1构造函数会多执行一次
通过call实现