js面向对象系列之四-寄生组合继承

寄生组合继承

上篇说了,组合继承很好的解决了类式和构造函数继承的缺点

但是他本身有个缺点就是父类的构造函数会执行两次,为了解决这个问题诞生出寄生组合继承

寄生组合继承主要是解决子类原型继承父类原型上的方法时,避免二次调用父类构造函数

那么该如何实现呢???

function inherit (o) {
    function A() {}
    A.prototype = o
    return new A()
}

function inheritObject(FatherClass,SonClass) {
    var x = inherit(FatherClass.prototype) //x继承了FatherClass.prototype
    
    SonClass.prototype = x //改写了SonClass的原型对象
    
    x.constructor = SonClass //将SonClass原型对象的constructor指向SonClass
}

//定义父类

function FatherClass(name) {
    this.name = name;
    this.list = ["王花花","李栓但","找可爽"]

}

//定义父类原型上的公用方法

FatherClass.prototype.checklist = function() {
    console.log(this.list)
}

//定义子类

function SonClass(name) {
    FatherClass.call(this,name)
}

inheritObject(FatherClass,SonClass)

var child1 = new SonClass("王花花")

console.log(child1)
    




寄生组合继承的难点主要在于这两个函数

inherit 这个函数主要是返回一个实例化中间实例化对象,这个实例化对象继承了FatherClass.prototype

所以inheritObject函数中的x 就是继承了 FatherClass.prototype,x就带有FatherClass.prototype上所拥有的公共方法

而这个方法要给到sonClass当中去,之前是采用sonClass.prototype  = a = new FatherClass();是因为a继承了FatherClass.prototype,现在我们有了x继承了FatherClass.prototype;

因此我们只需要将SonClass.prototype  = x 时即可,让new SonClass()继承SonClass.prototype上的方法也就是

FatherClass.prototype上的方法;

至于这个x.constructor = SonClass 这串代码主要是改写了SonClass的原型为x,而x本身是没有construcor属性的,而他又继承了

FatherClass.prototype,这这么个玩意是有constructor属性的,他的constructor属性指向FatherClass,为避免混乱重新设置其construcor属性并指向SonClass

至此四种继承类式-构造-组合-寄生组合

猜你喜欢

转载自blog.csdn.net/crq131290x/article/details/83584853
今日推荐