[js高手之路]原型式繼承與寄生式繼承

來源:互聯網
上載者:User

標籤:bsp   function   console   執行個體   複製   數組   參考型別   java   資料   

一、原型式繼承本質其實就是個淺拷貝,以一個對象為模板複製出新的對象

 1         function object( o ){ 2             var G = function(){}; 3             G.prototype = o; 4             return new G(); 5         } 6         var obj = { 7             name : ‘ghostwu‘, 8             age : 22, 9             show : function(){10                 return this.name + ‘,‘ + this.age;11             }12         };13         var obj2 = object( obj );14         console.log( obj2.name, obj.age, obj.show() );

object函數中,以對象o為模板,在object函數體裡面,定義一個建構函式,讓建構函式的原型對象(prototype)指向o,

返回建構函式的一個執行個體,這樣就可以訪問到對象o的所有屬性和方法.

二、因為原型式繼承是個淺拷貝,所以參考型別的資料共用在不同的執行個體之間

 1         function object( o ){ 2             var G = function(){}; 3             G.prototype = o; 4             return new G(); 5         } 6         var obj = { 7             skills : [ ‘php‘, ‘javascript‘ ] 8         }; 9         var obj2 = object( obj );10         obj2.skills.push( ‘python‘ );11         var obj3 = object( obj );12         console.log( obj3.skills ); //php,javascript,python

obj2改變了skills數組,obj3的skills結果就是其他執行個體改變的結果

三、在es5中,新增了一個函數Object.create()實現了原型式繼承

1         var obj = {2             skills : [ ‘php‘, ‘javascript‘ ]3         };4         var obj2 = Object.create( obj );5         obj2.skills.push( ‘python‘ );6         var obj3 = Object.create( obj );7         console.log( obj3.skills ); //php,javascript,python

四,寄生式繼承就是把原型式繼承再次封裝,然後在對象上擴充新的方法,再把新對象返回

 1         function object( o ){ 2             var G = function(){}; 3             G.prototype = o; 4             return new G(); 5         } 6         function CreateObj( srcObj ){ 7             var dstObj = object( srcObj ); 8             dstObj.sayName = function(){ 9                 return this.userName;10             }11             return dstObj;12         }13         var obj = {14             userName : ‘ghostwu‘,15         };16         var obj2 = CreateObj( obj );17         console.log( obj2.sayName() ); //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.