這個系列的第一部分,主要介紹了如何"封裝"資料和方法,以及如何從原型對象產生執行個體。
今天要介紹的是,對象之間的"繼承"的五種方法。
比如,現在有一個"動物"對象的建構函式。
function Animal(){
this.species = "動物";
}
還有一個"貓"對象的建構函式。
function Cat(name,color){
this.name = name;
this.color = color;
}
怎樣才能使"貓"繼承"動物"呢?
一、 建構函式綁定
第一種方法也是最簡單的方法,使用call或apply方法,將父物件的建構函式綁定在子物件上,即在子物件建構函式中加一行:
function Cat(name,color){
Animal.apply(this, arguments);
this.name = name;
this.color = color;
}
var cat1 = new Cat("大毛","黃色");
alert(cat1.species); // 動物
二、 prototype模式
第二種方法更常見,使用prototype屬性。
如果"貓"的prototype對象,指向一個Animal的執行個體,那麼所有"貓"的執行個體,就能繼承Animal了。
Cat.prototype = new Animal();
Cat.prototype.constructor = Cat;
var cat1 = new Cat("大毛","黃色");
alert(cat1.species); // 動物
代碼的第一行,我們將Cat的prototype對象指向一個Animal的執行個體。
Cat.prototype = new Animal();
它相當於完全刪除了prototype 對象原先的值,然後賦予一個新值。但是,第二行又是什麼意思呢?
Cat.prototype.constructor = Cat;
原來,任何一個prototype對象都有一個constructor屬性,指向它的建構函式。如果沒有"Cat.prototype = new Animal();"這一行,Cat.prototype.constructor是指向Cat的;加了這一行以後,Cat.prototype.constructor指向Animal。
alert(Cat.prototype.constructor == Animal); //true
更重要的是,每一個執行個體也有一個constructor屬性,預設調用prototype對象的constructor屬性。
alert(cat1.constructor == Cat.prototype.constructor); // true
因此,在運行"Cat.prototype = new Animal();"這一行之後,cat1.constructor也指向Animal!
alert(cat1.constructor == Animal); // true
這顯然會導致繼承鏈的紊亂(cat1明明是用建構函式Cat產生的),因此我們必須手動糾正,將Cat.prototype對象的constructor值改為Cat。這就是第二行的意思。
這是很重要的一點,編程時務必要遵守。下文都遵循這一點,即如果替換了prototype對象,
o.prototype = {};
那麼,下一步必然是為新的prototype對象加上constructor屬性,並將這個屬性指回原來的建構函式。
o.prototype.constructor = o;