JS 類繼承 原型繼承

來源:互聯網
上載者:User

標籤:對象   png   nbsp   技術   組合模式   模式   end   調用   方式   

參考文檔:JS原型繼承和類繼承

<script src="jquery-2.0.3.js"></script><script>/*//類繼承  var father=function(){    this.age=53;    this.say=function(){        console.log("name:"+this.name+",age:"+this.age);    } }; var child=function(){    this.name="child";    father.call(this); } var man=new child(); man.say();
console.log(man);
*/ //原型繼承 var father=function(){} father.prototype.a=function(){console.log(11)}; var child=function(){}; child.prototype=new father(); var man=new child(); man.a(); console.log(man);</script>

類繼承時列印man:

 

原型繼承時列印man:

 看似,原型繼承時,對象可以調用原型上的方法

 

類繼承的方法,每一次都會存到記憶體中,損耗效能,並且不容易擴充

原型繼承:很靈活,改變原型鏈即可,寫好extend就可以

 

通常繼承會匯聚兩種方式的優點,組合模式就是這樣做:用類繼承去繼承屬性(每個執行個體的屬性應該是私人的,不應該是共有的),用原型繼承去繼承方法

例如

  var father=function(){    this.age=53;     }; father.prototype.b=new function(){    console.log(this.age); } var child=function(){        father.call(this); }child.prototype=new father();var man=new child();console.log(man);

 **使用 Object.create()

var father ={    a:‘father‘,    b:function(){        console.log(this.a);    }}var obj=Object.create(father);console.dir(obj);

 

 

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.