DIV CSS 佈局教程網

JavaScript 定義類與物件的三種典型寫法
編輯:關於JavaScript     

JavaScript 沒有 class 關鍵字的年代(ES5 及以前),要「定義一個類」,社群累積了幾種常見寫法。理解它們,等於理解了原型鏈這套機制為什麼長這樣。

寫法一:用函數建構子 + prototype

最經典的方式,是把建構子寫成一個普通函數,用 this 掛上實例屬性,再用 prototype 掛上共享成員。

定義:

function classA(a) {
  this.aaa = a;              // 實例屬性
  this.methodA = function (ppp) {  // 實例方法
    alert(ppp);
  };
}

// 用 prototype 加入屬性,所有實例共享
classA.prototype.color = "red";

// 用 prototype 加入方法
classA.prototype.tellColor = function () {
  return "color of " + this.name + " is " + this.color;
};

使用:

var oClassA = new classA('This is a class example!'); // 實例化
var temp = oClassA.aaa;   // 使用屬性
oClassA.methodA(temp);    // 使用方法

這裡有個值得留意的細節:寫在建構子裡的 methodA 每 new 一次就會重新產生一份,佔用記憶體;掛在 prototype 上的 tellColor 則只有一份,被所有實例共用。實務上通常把方法放在 prototype,只把「每個實例值不同」的資料放在建構子裡。

寫法二:先實例化 Object 再擴充

定義:

var oClassA = new Object();          // 先建立基礎物件
oClassA.aaa = 'This is a class example!';  // 加入屬性
oClassA.methodA = function (ppp) {   // 加入方法
  alert(ppp);
};

使用:

var temp = oClassA.aaa;
oClassA.methodA(temp);

這種寫法其實是「單例物件」,它沒有建構子,也無法量產同類物件。若硬要在其上使用 prototype,語意會變得相當混亂,因為 prototype 的意義是「供建構子產生的實例共享」,而一般物件並不是建構子。因此實務上更乾淨的做法是直接用物件字面值:

寫法三:工廠函數與物件字面值

// 物件字面值:適合單一、不需量產的情境
var oClassA = {
  aaa: 'This is a class example!',
  methodA: function (ppp) {
    alert(ppp);
  }
};

oClassA.methodA(oClassA.aaa);
// 工廠函數:需要量產、又不想用 new 時
function createClassA(a) {
  return {
    aaa: a,
    methodA: function (ppp) {
      alert(ppp);
    }
  };
}

var obj = createClassA('hello');
obj.methodA(obj.aaa);

後續:ES6 的 class 語法糖

ES6 的 class 只是原型繼承的語法糖,本質不變:

class ClassA {
  constructor(a) {
    this.aaa = a;
  }
  methodA(ppp) {
    alert(ppp);
  }
}
ClassA.prototype.color = "red";

寫在 class body 裡的方法,自動掛在 prototype 上且不可枚舉,正好解決了寫法一中「方法被複製」與「可枚舉污染」的問題。

選擇建議

  • 只需要一個物件:用物件字面值,最簡潔;
  • 需要大量同結構物件:用 class(或 ES5 的建構子 + prototype);
  • 需要私有狀態與閉包封裝:考慮工廠函數,或 ES6 的 #private 欄位。
XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved