DIV CSS 佈局教程網

JavaScript建立物件(類)的八種寫法:從字面量到穩妥建構函數
編輯:關於JavaScript     

JavaScript 沒有 class 關鍵字的那段歲月裡,社群發展出了各式各樣建立「類」的手法。它們各有擅場,也各有明顯的短板。理解這八種模式的取捨,你才不會在任何情境下都反射性地寫出同一種結構。

1. Object 建構函數與物件字面量

var person = new Object();
person.name = "kevin";
person.age = 31;
alert(person.name);
alert(person["name"]);

另一種等價寫法是字面量。注意 person["5"] 這種寫法是合法的,而且用中括號取值時,key 裡可以有空格,例如 person["my age"]。

var person = {
  name: "Kevin",
  age: 31,
  5: "Test"
};
alert(person.name);
alert(person["5"]);

兩種寫法都能建立單一物件,但共同缺點很明顯:用同一個介面建立大量物件時,會產生大量重複程式碼。於是人們借用了工廠模式的概念。

2. 工廠模式

工廠模式是軟體工程裡廣為人知的設計模式,它抽象了建立物件的過程。ECMAScript 無法建立類,於是開發者用函數封裝「以特定介面建立物件」的細節:

function createPerson(name, age, job) {
  var o = new Object();
  o.name = name;
  o.age = age;
  o.job = job;
  o.sayName = function () {
    alert(this.name);
  };
  return o;
}
var person1 = createPerson("Nicholas", 29, "Software Engineer");
var person2 = createPerson("Greg", 27, "Doctor");

工廠模式解決了建立多個相似物件的問題,卻沒解決物件識別——你無從得知一個物件究竟是什麼型別。於是下一個模式出現了。

3. 建構函數模式

除了原生的 Object、Array,我們也能自訂建構函數來定義自己的物件型別:

function Person(name, age, job) {
  this.name = name;
  this.age = age;
  this.job = job;
  this.sayName = function () {
    alert(this.name);
  };
}
var person1 = new Person("Nicholas", 29, "Software Engineer");
var person2 = new Person("Greg", 27, "Doctor");

與 createPerson() 相比有三點不同:沒有顯式建立物件、直接把屬性與方法指派給 this、沒有 return 語句。

用 new 呼叫建構函數時,實際上會經歷四個步驟:

  1. 建立一個新物件。
  2. 把建構函數的作用域指派給這個新物件(因此 this 指向它)。
  3. 執行建構函數中的程式碼,為新物件加上屬性。
  4. 回傳這個新物件。

於是 person1 與 person2 各自保存著一份獨立實例,兩者都有 constructor 屬性並指向 Person:

alert(person1.constructor == Person); // true
alert(person2.constructor == Person); // true

constructor 最初是用來標識物件型別的,但要檢測型別,instanceof 更可靠。這裡建立的物件同時是 Object 與 Person 的實例:

alert(person1 instanceof Object); // true
alert(person1 instanceof Person); // true
alert(person2 instanceof Object); // true
alert(person2 instanceof Person); // true

能建立自訂建構函數、讓實例可以被標識為特定型別,正是建構函數模式勝過工廠模式之處。而 person1、person2 之所以也是 Object 的實例,是因為所有物件都繼承自 Object。

建構函數模式的問題

主要問題是:每個方法都要在每個實例上重新建立一次。ECMAScript 裡的函數就是物件,所以每定義一個函數,其實就是實例化了一個物件。從這個角度看,下面的寫法在邏輯上與前面等價:

function Person(name, age, job) {
  this.name = name;
  this.age = age;
  this.job = job;
  this.sayName = new Function("alert(this.name)"); // 邏輯上等同宣告函數
}

由此不難理解:每個 Person 實例裡都有一個獨立的 Function 實例。不同實例上的同名函數並不相等:

alert(person1.sayName == person2.sayName); // false

但建立兩個做完全相同事情的 Function 毫無意義——有 this 在,根本不必在執行前就把函數綁定到特定物件上。解法是把函數定義移到建構函數外面:

function Person(name, age, job) {
  this.name = name;
  this.age = age;
  this.job = job;
  this.sayName = sayName;
}
function sayName() {
  alert(this.name);
}
var person1 = new Person("Nicholas", 29, "Software Engineer");
var person2 = new Person("Greg", 27, "Doctor");

不過方法一多,全域函數就跟著暴增,自訂型別也就毫無封裝性可言了。這個問題該由原型模式接手。

4. 原型模式

function Person() {}
Person.prototype.name = "Nicholas";
Person.prototype.age = 29;
Person.prototype.job = "Software Engineer";
Person.prototype.sayName = function () {
  alert(this.name);
};
var person1 = new Person();
person1.sayName(); // "Nicholas"
var person2 = new Person();
person2.sayName(); // "Nicholas"
alert(person1.sayName == person2.sayName); // true

每加一個屬性就要敲一次 Person.prototype 太囉嗦,實務上更常用字面量一次重寫整個原型:

function Person() {}
Person.prototype = {
  name: "Nicholas",
  age: 29,
  job: "Software Engineer",
  sayName: function () {
    alert(this.name);
  }
};

結果看起來一樣,但有個關鍵差異:constructor 不再指向 Person。每建立一個函數就會同時建立它的 prototype 物件並自動賦予 constructor 屬性,而這裡的語法本質上完全替換了預設的 prototype,因此 constructor 變成新物件的 constructor(指向 Object)。此時 instanceof 仍正確,但 constructor 已無法用來判斷型別:

var friend = new Person();
alert(friend instanceof Object);        // true
alert(friend instanceof Person);        // true
alert(friend.constructor == Person);    // false
alert(friend.constructor == Object);    // true

若 constructor 的值對你很重要,可以手動補回去:

function Person() {}
Person.prototype = {
  constructor: Person,
  name: "Nicholas",
  age: 29,
  job: "Software Engineer",
  sayName: function () {
    alert(this.name);
  }
};

要牢記的是:實例中的指針只指向原型,並不指向建構函數。

原型模式的問題

首先它省略了為建構函數傳遞初始化參數的環節,所有實例預設都拿到相同的值。這還算小事,真正的問題來自它「共享」的本性——尤其是參考型別的屬性:

function Person() {}
Person.prototype = {
  constructor: Person,
  name: "Nicholas",
  age: 29,
  job: "Software Engineer",
  friends: ["Shelby", "Court"],
  sayName: function () {
    alert(this.name);
  }
};
var person1 = new Person();
var person2 = new Person();
person1.friends.push("Van");
alert(person1.friends); // "Shelby,Court,Van"
alert(person2.friends); // "Shelby,Court,Van"
alert(person1.friends === person2.friends); // true

改一個人的朋友名單,另一個人也跟著變了。

5. 建構函數模式與原型模式組合(最常用)

實務上最常見的做法是兩者混用:用建構函數定義實例屬性,用原型定義方法與共享屬性。每個實例都有自己的屬性副本,同時共享方法的參照,記憶體使用最經濟,而且支援向建構函數傳參。

function Person(name, age, job) {
  this.name = name;
  this.age = age;
  this.job = job;
  this.friends = ["Shelby", "Court"];
}
Person.prototype = {
  constructor: Person,
  sayName: function () {
    alert(this.name);
  }
};
var person1 = new Person("Nicholas", 29, "Software Engineer");
var person2 = new Person("Greg", 27, "Doctor");
person1.friends.push("Van");
alert(person1.friends); // "Shelby,Court,Van"
alert(person2.friends); // "Shelby,Court"
alert(person1.friends === person2.friends); // false
alert(person1.sayName === person2.sayName); // true

6. 動態原型模式

有 OO 語言經驗的人看到建構函數與原型分開寫,往往會覺得很彆扭。動態原型模式把資訊全部封裝進建構函數,只在必要時初始化原型——做法是檢查某個該存在的方法是否有效,來決定要不要初始化。

function Person(name, age, job) {
  // 屬性
  this.name = name;
  this.age = age;
  this.job = job;
  // 方法
  if (typeof this.sayName != "function") {
    Person.prototype.sayName = function () {
      alert(this.name);
    };
  }
}
var friend = new Person("Nicholas", 29, "Software Engineer");
friend.sayName();

7. 寄生建構函數模式

前面幾種模式都不合用時,可以考慮寄生模式。它的思路是:建立一個函數,只負責封裝建立物件的程式碼並回傳該物件,但表面上看起來像個正統的建構函數。

function Person(name, age, job) {
  var o = new Object();
  o.name = name;
  o.age = age;
  o.job = job;
  o.sayName = function () {
    alert(this.name);
  };
  return o;
}
var friend = new Person("Nicholas", 29, "Software Engineer");
friend.sayName(); // "Nicholas"

除了用 new 呼叫、名稱叫建構函數之外,它跟工廠模式幾乎一模一樣(建構函數在不回傳值時,預設會回傳新實例)。

8. 穩妥建構函數模式

所謂穩妥物件,指的是沒有公開屬性、方法也不參照 this 的物件。它最適合那些禁用 this 與 new 的安全環境,或需要防止資料被其他應用程式(例如 Mashup)竄改的場合。穩妥模式與寄生模式相似,但有兩點不同:實例方法不參照 this,且不使用 new 呼叫。

function Person(name, age, job) {
  // 建立要回傳的物件
  var o = new Object();
  // 這裡可以定義私有變量與函數
  // 加入方法(不參照 this,直接閉包 name)
  o.sayName = function () {
    alert(name);
  };
  return o;
}

八種寫法一路看下来,會發現它們其實是一條演化路線:從單純的字面量出發,為了重複使用而生的工廠模式、為了型別識別而出現的建構函數、為了共用方法而生的原型,最後收斂到兩者合流的組合模式。日常開發中,第五種(組合)與第六種(動態原型)就足夠應付絕大多數場景。

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