js 封裝類實現原型繼承

來源:互聯網
上載者:User

標籤:func   耦合   設定   style   tor   好處   使用   ==   儲存   

實現原理:定義一個封裝函數extend;該函數有2個參數,Child代表子類,Parent代表父類;在函數內,先定義一個空函數F, 用來實現功能中轉,設定F的原型為父類的原型,然後把空函數的執行個體傳遞給子類的原型,使用空函數的好處:避免直接執行個體化父類可能會帶來系統效能問題,比如父類的執行個體很大的話,執行個體化會佔用很多記憶體;

function extend(Child,Parent) {
    //Child表示子類,Parent表示父類
    // 首先定義一個空函數
   var F = function(){};

   // 設定空函數的原型為父類的原型
   F.prototype = Parent.prototype;

   // 執行個體化空函數,並把父類原型引用傳遞給子類
   Child.prototype = new F();

   // 重設子類原型的構造器為子類自身
   Child.prototype.constructor = Child;

    // 在子類中儲存父類的原型,避免子類與父類別結合程度
    Child.parent = Parent.prototype;

    if(Parent.prototype.constructor !== Parent) {
         // 檢測父類原型的構造器是否為原型自身
         Parent.prototype.constructor = Parent;
    }

}
測試代碼如下:
// 下面我們定義2個類A和類B,我們目的是實現B繼承於A
function A(x) {
   this.x = x;
   this.getX = function(){
      return this.x;
   }
}
A.prototype.add = function(){
   return this.x + this.x;
}
A.prototype.mul = function(){
   return this.x * this.x;
}
// 建構函式B
function B(x){
    A.call(this,x); // 繼承建構函式A中的所有屬性及方法
}
extend(B,A); // B繼承於A
var b = new B(10);
console.log(b.getX()); // 10
console.log(b.add()); // 20
console.log(b.mul()); //100

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.