DIV CSS 佈局教程網

JavaScript 建立自訂物件的方法總整理
編輯:關於JavaScript     

在 JavaScript 中建立物件的方式有很多種,本文把常見的做法逐一整理出來,並分析各自的優缺點。

Object 構造函式/物件字面量

最基本的方式,是先呼叫 Object 構造函式建立物件,再逐一加上屬性:

var student = new Object();
student.name = "xiao ming";
student.age = 20;
student.getName = function () {
  alert(this.name);
}

熟悉物件字面量的開發者,可以換成更簡潔的寫法:

var student = {
  name: "xiao hong",
  age: 18,
  getName: function () {
    alert(this.name);
  }
};

缺點:當需要用同一介面建立大量類似物件時,會產生大量重複程式碼,完全談不上重用。

工廠模式

工廠模式把建立物件的過程抽象出來,就像一個黑盒:你只要呼叫函式並傳入參數,就會得到一個對應的物件。它解決了建立多個相似物件的問題。

function studentFactory(name, age) {
  var student = new Object();
  student.name = name;
  student.age = age;
  student.sayName = function () {
    alert(this.name);
  }
  return student;
}
var p1 = studentFactory("ming", 20);
var p2 = studentFactory("hong", 18);

缺點:最大的問題是物件型別識別。用 p1 instanceof Object 只能判斷出它是 Object 型別,無法更具體判斷是哪種類型。此時更好的解法是建立一個 Student 構造函式,讓所有物件都屬於 Student 型別。

自訂型別的構造函式

構造函式可用來建立特定型別的物件:

function Student(name, age) {
  this.name = name;
  this.age = age;
  this.sayName = function () {
    alert(this.name);
  }
}
var p3 = new Student("ming", 20);
var p4 = new Student("hong", 18);
alert(p3 instanceof Student);
alert(p3.sayName == p4.sayName); // false

缺點:每個物件都會重新建立自己的方法,雖然這些方法功能相同,彼此卻不相等(p3.sayName 與 p4.sayName 不相等)。

原型模式

定義一個空函式,再把所有屬性與方法掛到原型上,這樣所有物件都會共用它們:

function Student() {};
Student.prototype.name = "ming";
Student.prototype.age = 20;
Student.prototype.friends = ['qi'];
Student.prototype.sayName = function () {
  alert(this.name);
};

缺點:有些屬性並不適合共享,例如 friends——每位同學的我的朋友大多不會相同,共享反而帶來問題。

構造函式與原型的組合

function Student(name, age, friends) {
  this.name = name;
  this.age = age;
  this.friends = friends;
}
Student.prototype = {
  constructor: Student,
  sayName: function () {
    alert(this.name);
  }
};

總結:構造函式與原型的組合是一種廣受認可的建立自訂型別的方法,也是上述方法中較優的一種——實例屬性各自獨立,方法則透過原型共享。

動態原型模式

它是構造函式與原型組合的一種優化:對於共用屬性與方法,一旦初始化過後就不必重複初始化,藉此提升效率。

function Student(name, age) {
  this.name = name;
  this.age = age;
  if ((typeof this.sayName) != "function") {
    Student.prototype.sayName = function () {
      alert(this.name);
    }
  }
}
var stu = new Student("ming", 20);
stu.sayName();

如此一來,建立多個 student 物件時,sayName 方法只會初始化一次。

穩妥構造函式模式

這個模式會避免使用 this 與 new,所有物件都沒有公共屬性,只能讀取變數的值而無法修改:

function Student(name, age) {
  var o = new Object();
  o.sayName = function () {
    alert(name);
  }
  return o;
}
var stu = Student("ming", 21);
stu.sayName();

以上整理了幾種常見的 JavaScript 建立自訂物件的方式,涵蓋了從最基礎到較進階的場景,希望對你的開發有所幫助。

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