組合繼承(combination inheritance),有時候也叫做僞經典繼承,指的是講原型鍊和借用構造函數的技術組合到一起,進而發揮二者之長。
思路:是使用原型鍊實作對原型屬性和方法的繼承,而通過借用構造函數來實作對執行個體屬性的繼承。這樣,通過在原型上定義方法來實作
了函數複用,又能夠保證每個執行個體都有自己的屬性,如下代碼:
<script type="text/javascript">
function SuperType(name){
this.name = name;
this.colors = ["red","blue","green"];
}
SuperType.prototype.sayName = function(){
alert(this.name);
}
function SubType(name,age){
//繼承了SuperType,同時傳遞還傳遞了參數
SuperType.call(this,name);
//執行個體屬性
this.age = age;
}
//繼承方法
SubType.prototype = new SuperType();
SubType.prototype.sayAge = function(){
alert(this.age);
}
var instance1 = new SubType("Nicholas",29);
instance1.colors.push("black");
alert(instance1.colors);//red,blue,green,black
instance1.sayName();
instance1.sayAge();
var instance2 = new SubType("Greg",29);
alert(instance2.colors);//red,blue,green
instance2.sayName();
instance2.sayAge();
</script>
組合繼承避免了原型鍊和借用構造函數的缺點,融合了他們的優點,成為JAVASCRIPT中最常用的繼承方式。
而且instancof和isPrototypeOf()也能夠用于識别基于組合繼承建立的對象。