本文是物件建立模式的下篇,承接上篇的命名空間、依賴定義、私有屬性、Revelation 模式與鏈式呼叫,繼續介紹四個更進階的模式。這些技巧能有效降低出錯機率,也能讓程式碼更為精簡。
函式語法糖是一個能為物件快速添加方法的擴充,原理來自 prototype 特性,實作相當簡短:
if (typeof Function.prototype.method !== "function") {
Function.prototype.method = function (name, implementation) {
this.prototype[name] = implementation;
return this;
};
}
擴充物件的時候就能寫成鏈式:
var Person = function (name) {
this.name = name;
}
.method('getName',
function () {
return this.name;
})
.method('setName', function (name) {
this.name = name;
return this;
});
如此就替 Person 加上了 getName 與 setName 兩個方法,而且因為 method 回傳 this,可以一路串下去。驗證結果:
var a = new Person('Adam');
console.log(a.getName()); // 'Adam'
console.log(a.setName('Eve').getName()); // 'Eve'
要注意的是,if (typeof Function.prototype.method !== "function") 這個前置判斷很重要——避免與其他類庫或未來的原生實作發生衝突,這也是擴充內建原型時的基本禮儀。
這個模式讓物件提供 set、get、isDefined 三個方法來管理「唯讀屬性」:set 只會保留第一次設定值,之後再設定都是無效的,藉此防止外部覆寫。實作如下:
var constant = (function () {
var constants = {},
ownProp = Object.prototype.hasOwnProperty,
// 只允許設置這三種類型的值
allowed = {
string: 1,
number: 1,
boolean: 1
},
prefix = (Math.random() + "_").slice(2);
return {
// 設置名稱為name的屬性
set: function (name, value) {
if (this.isDefined(name)) {
return false;
}
if (!ownProp.call(allowed, typeof value)) {
return false;
}
constants[prefix + name] = value;
return true;
},
// 判斷是否存在名稱為name的屬性
isDefined: function (name) {
return ownProp.call(constants, prefix + name);
},
// 獲取名稱為name的屬性
get: function (name) {
if (this.isDefined(name)) {
return constants[prefix + name];
}
return null;
}
};
} ());
兩個設計細節值得留意。一是 prefix = (Math.random() + "_").slice(2),替所有內部鍵名加上一層隨機前綴,避免使用者傳入 __proto__ 這類名稱時意外碰到 constants 物件本身。二是用 Object.prototype.hasOwnProperty.call 而非 in 來判斷存在性,確保只認自己的屬性,不會被原型鏈上的東西誤導。
驗證程式碼:
// 檢查是否存在
console.log(constant.isDefined("maxwidth")); // false
// 定義
console.log(constant.set("maxwidth", 480)); // true
// 重新檢測
console.log(constant.isDefined("maxwidth")); // true
// 嘗試重新定義
console.log(constant.set("maxwidth", 320)); // false
// 判斷原先的定義是否還存在
console.log(constant.get("maxwidth")); // 480
沙盒(Sandbox)模式為一個或多個模組提供獨立的上下文環境,彼此不互相干擾。舉例來說,某個 Sandbox 裡有 event、dom、ajax 三個方法,只要挑其中兩個組成環境,就和挑三個組成的環境完全隔離。
function Sandbox() {
// 將參數轉為數組
var args = Array.prototype.slice.call(arguments),
// 最後一個參數為callback
callback = args.pop(),
// 除最後一個參數外,其它均為要選擇的模塊
modules = (args[0] && typeof args[0] === "string") ? args : args[0],
i;
// 強制使用new操作符
if (!(this instanceof Sandbox)) {
return new Sandbox(modules, callback);
}
// 添加屬性
this.a = 1;
this.b = 2;
// 向this對象上需想添加模塊
// 如果沒有模塊或傳入的參數為 "*" ,則以為著傳入所有模塊
if (!modules || modules == '*') {
modules = [];
for (i in Sandbox.modules) {
if (Sandbox.modules.hasOwnProperty(i)) {
modules.push(i);
}
}
}
// 初始化需要的模塊
for (i = 0; i < modules.length; i += 1) {
Sandbox.modules[modules[i]](this);
}
// 調用 callback
callback(this);
}
// 默認添加原型對象
Sandbox.prototype = {
name: "My Application",
version: "1.0",
getName: function () {
return this.name;
}
};
這個建構函式的巧妙之處在於三點:用 args.pop() 把最後一個參數當回呼,剩下的才當模組清單,於是參數個數可以變化;用 if (!(this instanceof Sandbox)) 讓呼叫端不寫 new 也能運作;而模組本身是外掛式的,掛在 Sandbox.modules 上即可擴充。
接著定義三個預設模組:
Sandbox.modules = {};
Sandbox.modules.dom = function (box) {
box.getElement = function () {
};
box.getStyle = function () {
};
box.foo = "bar";
};
Sandbox.modules.event = function (box) {
// access to the Sandbox prototype if needed:
// box.constructor.prototype.m = "mmm";
box.attachEvent = function () {
};
box.detachEvent = function () {
};
};
Sandbox.modules.ajax = function (box) {
box.makeRequest = function () {
};
box.getResponse = function () {
};
};
每個模組都是一個函式,接收 box(也就是沙盒實例)並往上掛方法。呼叫方式如下:
// 調用方式
Sandbox(['ajax', 'event'], function (box) {
console.log(typeof (box.foo));
// 沒有選擇dom,所以box.foo不存在
});
Sandbox('ajax', 'dom', function (box) {
console.log(typeof (box.attachEvent));
// 沒有選擇event,所以event裡定義的attachEvent也不存在
});
Sandbox('*', function (box) {
console.log(box); // 上面定義的所有方法都可訪問
});
三種呼叫方式對應三種截然不同的上下文:第一種沒有 foo;第二種沒有 attachEvent,因為只載入了 ajax 與 dom;第三種則載入全部。注意第二種呼叫用了「多個字串參數」而非陣列,這也是前面 modules 判斷式所支援的寫法。
靜態成員(Static Members)是函式或物件提供的靜態屬性,可分為公有與私有,概念等同 C# 或 Java 裡的 public static 與 private static。
// 構造函數
var Gadget = function () {
};
// 公有靜態方法
Gadget.isShiny = function () {
return "you bet";
};
// 原型上添加的正常方法
Gadget.prototype.setPrice = function (price) {
this.price = price;
};
// 調用靜態方法
console.log(Gadget.isShiny()); // "you bet"
// 創建實例,然後調用方法
var iphone = new Gadget();
iphone.setPrice(500);
console.log(typeof Gadget.setPrice); // "undefined"
console.log(typeof iphone.isShiny); // "undefined"
Gadget.prototype.isShiny = Gadget.isShiny;
console.log(iphone.isShiny()); // "you bet"
這段程式說明了靜態與實例方法的界線:靜態方法掛在建構函式上,實例取不到;實例方法掛在原型上,建構函式本身也取不到。最後一行手動把靜態方法「提升」到原型上,實例才終於能呼叫它——這也解釋了為什麼有些類庫會同時提供靜態與實例兩種呼叫方式。
var Gadget = (function () {
// 靜態變量/屬性
var counter = 0;
// 閉包返回構造函數的新實現
return function () {
console.log(counter += 1);
};
} ()); // 立即執行
var g1 = new Gadget(); // logs 1
var g2 = new Gadget(); // logs 2
var g3 = new Gadget(); // logs 3
雖然每次都是 new 出來的新物件,數字卻持續遞增。原因是 counter 位於 IIFE 的作用域內,所有實例共用同一個变数,而外部完全無法直接存取它。
var Gadget = (function () {
// 靜態變量/屬性
var counter = 0,
NewGadget;
//新構造函數實現
NewGadget = function () {
counter += 1;
};
// 授權可以訪問的方法
NewGadget.prototype.getLastId = function () {
return counter;
};
// 覆蓋構造函數
return NewGadget;
} ()); // 立即執行
var iphone = new Gadget();
iphone.getLastId(); // 1
var ipod = new Gadget();
ipod.getLastId(); // 2
var ipad = new Gadget();
ipad.getLastId(); // 3
差別在於:這次多了一個「授權方法」getLastId,讓外部得以讀取私有靜態變數的值,同時仍然無法改寫它。這種「只讀公開、寫入私有」的組合,是封裝私有狀態最實用的形式。
這是物件建立模式的下篇。上下兩篇合計九種模式,都是我們在日常 JavaScript 開發中經常會用到的物件建立手法。它們各自解決不同側面的問題——命名衝突、依賴管理、資訊隱藏、介面簡潔、環境隔離、狀態共用——不存在絕對的優劣,關鍵在於依場景選擇合適的模式,並理解每個模式背後所付出的代價。