1、借助call
function Parent(){
this.name='parent'
}
function Child(){
Parent1.call(this)
}
var a=new Child();
子类虽然能够拿到父类的属性值,但是,子类无法拿到父类中的方法。
2、借助原型链
function Parent(){
this.name='parent'
this.arr=[1,2,3]
}
function Child(){
}
Child.prototype=new Parent
var a=new Child();
子类能拿到父类的属性,也能拿到父类的方法。
但是,var a=new Child();var b=new Child();实例a和实例b使用的是同一个原型对象,如果a.arr.push(23),那么b.arr也会改变。
3、将前两种结合
function Parent(){
this.name='parent'
this.arr=[1,2,3]
}
function Child(){
Parent.call(this)
}
Child.prototype=new Parent
var a=new Child();
这种方式Parent构造函数会执行两次
4、组合继承的优化
function Parent(){
this.name='parent'
this.arr=[1,2,3]
}
function Child(){
Parent.call(this)
}
Child.prototype=Parent.prototype
var a=new Child();
将父类的原型对象直接给子类的原型对象,父类构造函数只执行一次。
但是子类的构造函数会显示位Parent,我们不能手动更改Child.prototype.constructor,因为一更改,那么Parent.prototype.constructor就也变了。
5、组合继承的优化2,寄生组合继承
function Parent(){
this.name='parent'
this.arr=[1,2,3]
}
function Child(){
Parent.call(this)
}
Child.prototype=Object(Parent.prototype);
Child.prototype.constructor=Child
var a=new Child();
Object(Parent.prototype)产生一个以Parent.prototype为原型的新对象。
同时手动更改Child.prototype.constructor