javascript的繼承方法

來源:互聯網
上載者:User

標籤:整合   var   解決   asc   繼承   strong   繼承方式   一個   優缺點   

一、建構函式繼承

  該方法最簡單,使用call或者apply方法,將父物件的建構函式綁定到子物件上。

function Parent(name){    this.name = name;    this.color = [‘red‘,‘green‘];        this.getInfo = function(){        alert(this.name + ‘喜歡的顏色:‘+ this.color)    }}function Child(name){    Parent.call(this,name);}var child1 = new Child(‘張三‘);child1.color.push(‘black‘);child1.getInfo();// 張三喜歡的顏色: red,green,blackvar child2 = new Child(‘李四‘);child2.getInfo();    // 李四喜歡的顏色: red,green

這樣實現有一個弊端,就是每new一次,執行個體對象的屬性和方法都會開闢記憶體空間,比較浪費記憶體,缺乏效率。

為瞭解決記憶體消耗問題,下面介紹一下原型鏈繼承

二、原型鏈繼承

  我們知道每一個建構函式都有一個prototype屬性,指向另一個對象。這個對象的所有方法和屬性都會被建構函式的執行個體繼承。所以我們可以把不變的屬性和方法定義在prototype對象上。

  

function Parent(name){this.name = name;this.color = [‘red‘,‘green‘];}//不變的屬性或方法定義在prototype上,prototype對象上的方法是共用的, 每次new Parent()時不需要重新開闢記憶體空間Parent.prototype.getInfo = function(){alert(this.name + ‘喜歡的顏色:‘+ this.color)}function Child(name){}Child.prototype = new Parent();var child1 = new Child(‘張三‘);child1.color.push(‘black‘);  //此操作會改變Parent建構函式的color屬性 color值變成[red,green,black] child1.getInfo(); //undefined喜歡的顏色 : red,green,black var child2 = new Child(‘李四‘); child2.getInfo();//undefined喜歡的顏色 : red,green,black ,

  

原型鏈繼承存雖然解決了建構函式消耗記憶體的問題,但是這種繼承方式存在兩個問題:

  問題1: 建立子類型的執行個體時,無法向父類建構函式傳遞參數(例子中:Childh的name參數無法傳給Parent中)。

  問題2:如果構造行數的屬性是參考型別,並且整合後改變了其值,則父建構函式中得值會被更改(例子中的color屬性被更改了)

三、混合繼承(建構函式和原型結合方式)

  借鑒以上兩種方式的優缺點,採用建構函式和原型結合方式

function Parent(name){this.name = name;this.color = [‘red‘,‘green‘];}//不變的屬性或方法定義在prototype上,prototype對象上的方法是共用的, 每次new Parent()時不需要重新開闢記憶體空間Parent.prototype.getInfo = function(){alert(this.name + ‘喜歡的顏色:‘+ this.color)}function Child(name){//通過call或者apply實現繼承Parent,相當於重新建立了Parent屬性的副本//Parent中的屬性會copy出一份,重新開闢記憶體空間Parent.call(this,name); //Parent.apply(this,[name]);}Child.prototype = new Parent();var child1 = new Child(‘張三‘);child1.color.push(‘black‘);child1.getInfo(); //張三喜歡的顏色 : red,green,blackvar child2 = new Child(‘李四‘);child2.getInfo();//李四喜歡的顏色 : red,green

  

javascript的繼承方法

聯繫我們

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