JS 面向对象之继承---多种组合继承详解
这一次要讲 组合、原型式、寄生式、寄生组合式继承方式。
1.组合继承:又叫伪经典继承,是指将原型链和借用构造函数技术组合在一块的一种继承方式。
下面来看一个例子:
functionSuperType(name){ this.name=name; this.colors=["red","blue","green"]; } SuperType.prototype.sayName=function(){ alert(this.name); } functionSubType(name,age){ SuperType.call(this,name); this.age=age; } //继承方法 SubType.prototype=newSuperType(); SubType.prototype.sayAge=function(){ alert(this.age); } varinstance1=newSubType("Nicholas",29); instance1.colors.push("black"); alert(instance1.colors);//red,blue,green,black instance1.sayName();//Nicholas instance1.sayAge();//29 varinstance2=newSubType("Greg",27); alert(instance2.colors);//red,blue,green instance2.sayName();//Greg instance2.sayAge();//27
组合继承避免了原型链和借用构造函数的缺陷,融合它们的优点。
2.原型式继承
可以在不必预先定义构造函数的情况下实现继承,其本质是执行对给定对象的浅复制。而复制得到的副本还可以得到进一步的改造。
functionobject(o){ functionF(){}; F.prototype=o; returnnewF; } varperson={ name:"Nicholas", friends:["Shelby","Court","Van"] }; varantherPerson=object(person); antherPerson.name="Greg"; antherPerson.friends.push("Rob"); varantherPerson=object(person); antherPerson.name="Linda"; antherPerson.friends.push("Barbie"); alert(person.friends);//Shelby,Court,Van,Rob,Barbie
3.寄生式继承
与原型式继承非常相似,也是基于某个对象或某些信息创建一个对象,然后增强对象,最后返回对象。为了解决组合继承模式由于多次调用超类型构造函数而导致的低效率问题,可以将这个模式与组合继承一起使用。
functionobject(o){ functionF(){}; F.prototype=o; returnnewF; } functioncreateAnother(original){ varclone=object(original); clone.sayHi=function(){ alert("Hi"); }; returnclone; } varperson={ name:"Nicholas", friends:["Shelby","Court","Van"] }; varanotherPerson=createAnother(person); anotherPerson.sayHi();
4.寄生组合式继承
集寄生式继承和组合继承的优点与一身,是实现基本类型继承的最有效方式。
//继承原型 functionextend(subType,superType){ functionF(){}; F.prototype=superType.prototype; varprototype=newF; prototype.constructor=subType; subType.prototype=prototype; } //超类方法 functionSuperType(name){ this.name=name; this.colors=["red","blue","green"]; } SuperType.prototype.sayName=function(){ returnthis.name; } //子类方法 functionSubType(name,age){ SuperType.call(this,name); this.age=age; } //继承超类的原型 extend(SubType,SuperType); //子类方法 SubType.prototype.sayAge=function(){ returnthis.age; } varinstance1=newSubType("Shelby"); varinstance2=newSubType("Court",28); instance1.colors.push('black'); alert(instance1.colors);//red,blue,green,black alert(instance2.colors);//red,blue,green alert(instance1instanceofSubType);//true alert(instance1instanceofSuperType);//true
这段例子的高效率体现在它只调用了一次SuperType构造函数,并且因此避免了在SubType.prototype上面创建不必要的多余的属性。与此同时,原型链还能保持不变。因此,还能正常使用instanceof和isPrototypeOf()。开发人员普遍认为寄生组合式继承是引用类型最理想的继承范式。
以上这篇JS面向对象之继承---多种组合继承详解就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持毛票票。