JAVASCRIPT繼承--混合方式

來源:互聯網
上載者:User

 實現JavaScript繼承的最簡單的方式是call方法(或者apply方法)及原型鏈方法,但這兩種方法都有缺陷,而其混合體就是很好的繼承實現方式。下面舉例說明:
[javascript]
function Animal(age){ 
    this.age = age; 
} 
 
Animal.prototype.sayAge = function(){ 
    window.alert("My age is "+this.age+"!"); 
}; 
 
function Dog(age,name){ 
    Animal.call(this,age); 
    this.name = name; 
} 
Dog.prototype = new Animal(); 
Dog.prototype.sayName = function(){ 
    window.alert("I am a "+this.name+"!"); 
}; 
 
var dog = new Dog(15,"dog"); 
dog.sayName(); 
dog.sayAge(); 

  對於類Animal來說,它有一個欄位屬性age及函數屬性sayAge,sayAge方法的定義採用的是原型方式。Dog類要繼承Animal,其欄位屬性除了age外還有name,通過Animal.call(this,age);可以實現Dog繼承Animal的欄位屬性age並將其初始化了。call方法的第一個參數為繼承的類的this指標,第二個參數為Animal類的建構函式的參數。實際上,只是通過call方法就可以實現繼承,但唯一的要求是父類的函數屬性要在建構函式中定義,這對於這裡的函數屬性使用原型方式定義來說就不適合了(採用原型方式定義函數屬性比在建構函式內定義更直觀一些)。
作者:hfmbook

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.