DIV CSS 佈局教程網

JavaScript 以建構函式建立物件的經典模式
編輯:關於JavaScript     

1. 概述

用建構函式建立物件時,有個很常見的疏失:忘了寫 new。一旦漏掉,函式內的 this 會指向全域物件(嚴格模式下則是 undefined),函式本身預設回傳 undefined,結果就是什麼都拿不到,而且還會污染全域。

比較穩健的做法是多包一層工廠函式,把 new 封裝在內部,讓呼叫端不必記得加:

 function Student(props){
  this.name  = props.name  || '匿名';
  this.grade = props.grade || 1;
}

Student.prototype.hello = function(){
  alert('Hello, ' + this.name + '!');
};

function createStudent(props){
  return new Student(props || {});
}

如此一來,呼叫 createStudent({name: '小明'}) 與 createStudent() 都不會出錯,未傳參數時也有預設值可用。

要牢記的原則是:函式若沒有顯式寫出 return xxx;,回傳值就是 undefined。這也是為什麼建構函式加上 new 之後反而能拿到物件——那是 new 運算子的機制,不是函式自身的行為。

2. 實作示例

用建構函式定義 Cat,讓所有 Cat 物件都有一個 name 屬性,並共享同一個 say() 方法:

 'use strict';

function Cat(name) {
  this.name = name;
}

Cat.prototype.say = function(){
  return ('Hello, ' + this.name + '!');
};

// 測試
var kitty    = new Cat('Kitty');
var doraemon = new Cat('哆啦A夢');

if (kitty &&
    kitty.name === 'Kitty' &&
    kitty.say &&
    typeof kitty.say === 'function' &&
    kitty.say() === 'Hello, Kitty!' &&
    kitty.say === doraemon.say) {

  alert('測試通過!');
} else {
  alert('測試失敗!');
}

測試條件中的 kitty.say === doraemon.say 是重點,它驗證了「方法共享」。

3. 為什麼方法要掛在 prototype 上

如果把 say 寫在建構函式內部:

 function Cat(name) {
  this.name = name;
  this.say = function(){ return 'Hello, ' + this.name + '!'; };
}

那麼每 new Cat() 一次,都會重新產生一份 say 函式物件。建立一萬隻貓就有一萬份一模一樣的函式,白白浪費記憶體。

掛在 Cat.prototype.say 上則只會存在一份,所有實例透過原型鏈共用同一個參照。這正是「屬性歸實例、方法歸原型」的基本分工原則。

4. 建構函式的其他防護手法

除了工廠函式,還有兩種常見做法:

 // 手法一:在函式內自行判斷,若沒用 new 就幫你補上
function Cat(name) {
  if (!(this instanceof Cat)) {
    return new Cat(name);
  }
  this.name = name;
}

// 手法二:用 ES6 class,它天生就禁止使用 new 以外的方式呼叫
class Cat2 {
  constructor(name) {
    this.name = name;
  }
  say() {
    return 'Hello, ' + this.name + '!';
  }
}

Cat2('Kitty');   // TypeError: Class constructor Cat2 cannot be invoked without 'new'

ES6 的 class 基本上只是原型繼承的語法糖,但它強制要求以 new 呼叫、方法自動掛在 prototype 上、且宣告不會被提升,這些約束反而讓程式碼更不容易出錯。新專案可直接採用。

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