[js高手之路]寄生組合式繼承的優勢

來源:互聯網
上載者:User

標籤:回顧   targe   obj   teacher   對象   javascrip   調用   html   不能   

在之前javascript物件導向系列的文章裡面,我們已經探討了組合繼承和寄生繼承,回顧下組合繼承:

 1         function Person( uName ){ 2             this.skills = [ ‘php‘, ‘javascript‘ ]; 3             this.userName = uName; 4         } 5         Person.prototype.showUserName = function(){ 6             return this.userName; 7         } 8         function Teacher ( uName ){ 9             Person.call( this, uName );10         }11         Teacher.prototype = new Person();12 13         var oT1 = new Teacher( ‘ghostwu‘ );14         oT1.skills.push( ‘linux‘ );15         var oT2 = new Teacher( ‘ghostwu‘ );16         console.log( oT2.skills ); //php,javascript17         console.log( oT2.showUserName() ); //ghostwu

組合繼承有個缺點,父類的建構函式會被調用兩次.

第11行,設定子類原型對象(prototype),調用了第一次

第9行,執行個體化對象的時候,又調用一次

建構函式的目的是為了複製屬性,第9行肯定是不能少的,第11行的目的是為了擷取到父類原型對象(prototype)上的方法,基於這個目的,有沒有別的方法

可以做到 在不需要執行個體化父類建構函式的情況下,也能得到父類原型對象上的方法呢? 當然可以,我們可以採用寄生式繼承來得到父類原型對象上的方法

 1         function Person( uName ){ 2             this.skills = [ ‘php‘, ‘javascript‘ ]; 3             this.userName = uName; 4         } 5         Person.prototype.showUserName = function(){ 6             return this.userName; 7         } 8         function Teacher ( uName ){ 9             Person.call( this, uName );10         }11 12         function object( o ){13             var G = function(){};14             G.prototype = o;15             return new G();16         }17 18         function inheritPrototype( subObj, superObj ){19             var proObj = object( superObj.prototype ); //複製父類superObj的原型對象20             proObj.constructor = subObj; //constructor指向子類建構函式21             subObj.prototype = proObj; //再把這個對象給子類的原型對象22         }23 24         inheritPrototype( Teacher, Person );25 26         var oT1 = new Teacher( ‘ghostwu‘ );27         oT1.skills.push( ‘linux‘ );28         var oT2 = new Teacher( ‘ghostwu‘ );29         console.log( oT2.skills ); //php,javascript30         console.log( oT2.showUserName() ); //ghostwu

 

其實,說白了寄生組合式繼承就是一個借用建構函式 + 相當於淺拷貝父類的原型對象

 

[js高手之路]寄生組合式繼承的優勢

聯繫我們

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