DIV CSS 佈局教程網

JavaScript 建立物件的多種寫法整理
編輯:JavaScript技巧     

除了天天在寫的那一種,JavaScript 其實還有好幾種建立物件的模式。把它們放在一起對照,才看得出各自的取捨在哪裡。

1. 建構函數模式

自訂一個建構函數,用 new 呼叫它來產生實例。

function cons(name, age){
  this.name = name;
  this.age = age;
  this.getMes = function(){
    console.log(`my name is ${this.name}, this year ${this.age}`);
  };
}
var mesge = new cons('will', 21);
mesge.getMes();

問題是 getMes 每建立一個實例就多一份,功能相同卻佔了 n 份記憶體。

2. 工廠模式

把建立物件的細節封裝在函數裡,用 new Object() 產生後再掛屬性,最後回傳。

function cons(name, age){
  var obj = new Object();
  obj.name = name;
  obj.age = age;
  obj.getMes = function(){
    console.log(`my name is ${this.name}, this year ${this.age}`);
  };
  return obj;
}
var mesge = cons('will', 21);
mesge.getMes();

它擺脫了 new 的束縛,但依然沒解決方法重複建立的問題,而且回傳的物件與建構函數之間失去了原型上的連結,instanceof 無法辨識。

3. 字面量模式

var cons = {
  name: 'will',
  age: 21,
  getMes: function(){
    console.log(`my name is ${this.name}, this year ${this.age}`);
  }
};
cons.getMes();

適合單一物件,但要造十個就會產生大量重複程式碼。

4. 原型模式

把成員掛在原型上,所有實例共享同一份。

function cons(){}
cons.prototype.name = "will";
cons.prototype.age = 21;
cons.prototype.getMes = function(){
  console.log(`my name is ${this.name}, this year ${this.age}`);
};

var mesge = new cons();
mesge.getMes();
var mesge1 = new cons();
mesge1.getMes();
console.log(mesge.getMes === mesge1.getMes); // true

共享省了記憶體,但代價是所有實例預設共用同一份資料——原型上的陣列或物件若被其中一個實例改動,其他實例全都受影響。

5. 組合模式

把兩者合起來才是實務上的正解:實例屬性放在建構函數裡,方法與共享屬性放在原型上。這樣每個實例都有自己的屬性副本,同時共享方法的參照,既省記憶體又不會互相干擾,還能正常接收參數。

function cons(name, age){
  this.name = name;
  this.age = age;
  this.friends = ["arr", "all"];
}
cons.prototype = {
  getMes: function(){
    console.log(`my name is ${this.name}, this year ${this.age}`);
  }
};

var mesge = new cons("will", 21);
var mesge1 = new cons("jalo", 21);

mesge.friends.push('wc');
console.log(mesge.friends);   // ["arr", "all", "wc"]
console.log(mesge1.friends);  // ["arr", "all"],互不影響
console.log(mesge.friends === mesge1.friends);   // false
console.log(mesge.getMes === mesge1.getMes);     // true

這也是目前最廣為採用的自訂物件模式。

ES6 的 Class 語法

ES6 引入 class 之後,建立物件與繼承都直觀多了。本質上它仍是原型繼承的語法糖,但可讀性提升不少。

class Cons {
  constructor(name, age){
    this.name = name;
    this.age = age;
  }
  getMes(){
    console.log(`hello ${this.name} !`);
  }
}
let mesge = new Cons('啦啦啦', 21);
mesge.getMes();

constructor 就是建構函數,this 則指向被建立的實例。方法直接寫在類別 body 中,會自動掛到原型上,正好對應上面說的組合模式。

繼承則靠 extends,並在子類建構式中以 super() 呼叫父類建構式。

class Ctrn extends Cons {
  constructor(name, anu){
    super(name);
    this.anu = anu;
  }
  ingo(){
    console.log(`my name is ${this.name}, this year ${this.anu}`);
  }
}
let ster = new Ctrn('will', 21);
ster.ingo();
ster.getMes();

注意子類若在建構式中用到 this,必須先呼叫 super(),否則會直接拋出錯誤——這是 class 語法帶來的硬性檢查,在以往的原型寫法裡並不會發生。

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