DIV CSS 佈局教程網

JavaScript 物件導向繼承:兩種經典寫法與效能取捨
編輯:JavaScript基礎知識     

JavaScript 問世至今已二十餘年,對它的評價仍然兩極。很多人說它不算物件導向語言——型別系統極度寬鬆,又沒有編譯器。這確實給了開發者很大的自由,也帶來一些缺陷。

但即使 JavaScript 不是傳統意義的物件導向語言,我們仍可以模仿其他語言的做法,在這裡實作出物件導向的風格。下面是兩種常見且經典的繼承寫法。

寫法一:原型繼承(new + prototype)

// 定義 Pet 物件,保存名字與腿的數量
var Pet = function (name, legs) {
  this.name = name;
  this.legs = legs;
};

// 在原型上建立方法
Pet.prototype.getDetails = function () {
  return this.name + " has " + this.legs + " legs ";
};

// 定義 Cat,繼承自 Pet
var Cat = function (name) {
  Pet.call(this, name, 4);      // 呼叫父類的建構函式
};

Cat.prototype = new Pet();      // 這一行完成繼承

// 為貓加上自己的方法
Cat.prototype.action = function () {
  return "Catch a bird";
};

var petCat = new Cat("felix");

console.log(petCat.getDetails());   // "felix has 4 legs"
console.log(petCat.action());       // "Catch a bird"

petCat.name = "sylvester";
petCat.legs = 7;                    // 屬性可以被外部任意修改
console.log(petCat.getDetails());   // "sylvester has 7 legs"

這個寫法執行起來沒問題,但整體風格略顯冗長,也不夠優雅。而且外部仍可以任意修改屬性——它沒有對繼承而來的屬性提供任何保護。

寫法二:函式繼承(閉包 + 私有變數)

// 定義 pet 物件。名字可改,腿數不可改,實現變數私有化
var pet = function (name, legs) {
  var that = {
    name: name,
    getDetails: function () {
      return that.name + " has " + legs + " legs ";
    }
  };
  return that;
};

// 定義 cat,繼承自 pet
var cat = function (name) {
  var that = pet(name, 4);      // 承接 pet 的屬性與方法

  that.action = function () {   // 加上貓特有的方法
    return "Catch a bird";
  };

  return that;
};

var petCat2 = cat("Felix");

console.log(petCat2.getDetails());   // "felix has 4 legs"
console.log(petCat2.action());       // "Catch a bird"

petCat2.name = "sylvester";
petCat2.legs = 7;                    // 加到 this 上沒有用
console.log(petCat2.getDetails());   // "sylvester has 4 legs"

這裡省去了 new 與 prototype,靠閉包特性把 legs 藏在函式作用域中,外部改不到。注意最後一行:即使指派了 petCat2.legs = 7,getDetails() 讀的仍是閉包裡那個 4。

效能取捨

原型繼承的記憶體效率高:不論被繼承多少次,原型上的屬性與方法只存在一份。

函式繼承則是每個新實例都會建立一份屬性與方法,實例一多,記憶體消耗就很可觀。解法是把較大的屬性或方法抽出來放在一個共用物件中,作為參數傳進建構函式,讓所有實例參照同一份資源,而不是各自複製。

現代寫法

ES6 的 class 語法讓原型繼承變得一目了然,同時保留了原型鏈的記憶體優勢:

class Pet {
  constructor(name, legs) {
    this.name = name;
    this.legs = legs;
  }
  getDetails() {
    return `${this.name} has ${this.legs} legs`;
  }
}

class Cat extends Pet {
  constructor(name) {
    super(name, 4);
  }
  action() {
    return "Catch a bird";
  }
}

若需要真正的私有欄位,ES2022 的 # 前綴才是標準做法:

class Pet {
  #legs;
  constructor(name, legs) {
    this.name = name;
    this.#legs = legs;
  }
  getDetails() {
    return `${this.name} has ${this.#legs} legs`;
  }
}

上面兩種傳統寫法都還值得理解——讀懂它們,你才知道 class 語法糖底下實際發生了什麼。但新專案請直接用 class 與 #private,程式碼意圖清楚,也不必再手動接 prototype 鏈。沒有哪種方法絕對好或絕對壞,重點是場景與維護成本。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved