Javascript物件導向編程(二) 建構函式的繼承

來源:互聯網
上載者:User

這個系列的第一部分,主要介紹了如何"封裝"資料和方法,以及如何從原型對象產生執行個體。

今天要介紹的是,對象之間的"繼承"的五種方法。

比如,現在有一個"動物"對象的建構函式。

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;

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.