Javascript編程之繼承執行個體匯總_javascript技巧

來源:互聯網
上載者:User

本文執行個體講述了Javascript編程之繼承。分享給大家供大家參考,具體如下:

這篇文字是在看完《Javascript 王者歸來》後的整理總結,文章詳細章節在 第21章 P537

繼承一般要實現以下三層含義:

1)子類執行個體可以共用父類的方法;
2)子類可以覆蓋父類的方法或者擴充新的方法;
3)子類和父類都是子類執行個體的類型。

一、構造繼承法

子類中調用父類的建構函式來維護的,該繼承法能實現多重繼承,但只能繼承父類的共有方法,無法繼承靜態方法,而且不能用instanceof來驗證執行個體。

function a(){  this.say=function(){  alert("happy new year!");  }}function b(){  a.apply(this,arguments);}a.prototype.fuck=function(){  alert("%^&%^&%&^%&");}var oB=new b();alert(oB instanceof a);// falseoB.say();       // happy new yearoB.fuck();       // 讀不到

二、原型繼承法/經典繼承法

該繼承法是通過複製已經存在的原型對象來實現行為重用,讓對象執行個體共用原型對象的屬性。支援多重繼承,繼承原型靜態方法,能用instanceof來驗證執行個體。

function a(){ this.say=function(){ alert("happy new year!"); }}function b(){}a.prototype.fuck=function(){  alert("%^&%^&%&^%&");}a.prototype.z=123;b.prototype=new a();var oB=new b();alert(oB instanceof a); // truealert(oB.z);      // 123oB.say();        // happy new yearoB.fuck();       // %^&%^&%&^%&

三、執行個體繼承法/寄生建構函式模式

構造法不能繼承類型的靜態方法,原型繼承得不完善(某些核心對象的不可枚舉方法不能繼承),而執行個體繼承法能對原生核心對象或者DOM對象進行繼承,它通過在類型中構造對象並返回的辦法來實現繼承,因此instanceof驗證會是false,不支援多重繼承。

function a(){ var oA=new Array(); oA.say=function(){   alert("hello A!"); } return oA;}var obj=new a();alert(obj instanceof a); // falseobj.say();

四、拷貝繼承法

該方法通過拷貝基類對象的所有可枚舉屬性和方法來類比繼承,因此它可以類比多繼承,但不能枚舉的就無法繼承;它可以繼承父類的靜態方法;

function a(){  this.num=123;  this.say=function(){  alert("happy new year!");  }}function b(){  this.extends=function(obj){    for(each in obj){      this[each]=obj[each];    }  }}var oB=new b();oB.extends(new a());alert(oB instanceof a); // falsealert(oB.num);     // 123oB.say();        // happy new year

五、混合繼承法

顧名思義就是把上面幾種繼承法綜合起來,取長補短,讓繼承更完善。常見的有 構造+原型繼承:偽經典繼承

function a(){  this.num=123;  this.say=function(){  alert("happy new year!");  }}function b(){  a.apply(this);}b.prototype=new a();b.prototype.z=123;var oB=new b();alert(oB instanceof a); // truealert(oB.num);     // 123oB.say();        // happy new year

六、各種繼承法的優缺點

希望本文所述對大家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.