有時候我們不希望某個類別天生就龐大無比、一次包辦所有職責,這時裝飾者模式就能派上用場。它可以在不動原物件的前提下,動態地為對象加上額外職責,而且不影響同一類別派生的其他實例。具體做法是「把一個物件放進另一個物件裡」,形成一條包裝鏈。
一、不改動原函式,替它加上新功能
最直覺的做法是保存原參照:
window.onload = function() { console.log(1); }; var _onload = window.onload || function() {}; window.onload = function() { _onload(); console.log(2); }
這個寫法有兩個問題:一是必須維護 _onload 這個中間變數;二是可能遇到 this 被劫持。在 window.onload 這個例子裡沒出事,純粹是因為呼叫 _onload() 時 this 剛好也指向 window,跟原狀況一致。
換個例子就會爆掉:
var _getElementById = document.getElementById; document.getElementById = function(id) { console.log(1); return _getElementById(id); } // 報錯"Uncaught TypeError: Illegal invocation"
原因很單純:_getElementById 是裸呼叫,this 指向 window,但這個原生方法預期 this 必須是 document。解法是用 call 把上下文補回去:
var _getElementById = document.getElementById; document.getElementById = function(id) { console.log(1); return _getElementById.call(document, id); }
二、用 AOP 裝飾函式
把上面這套手法抽象出來,就得到面向切面程式設計(AOP)的雛形。前置裝飾:
/* 讓新添加的函數在原函數之前執行(前置裝飾)*/ Function.prototype.before = function(beforefn) { var _self = this; return function() { beforefn.apply(this, arguments); // 新函數接收的參數會被原封不動的傳入原函數 return _self.apply(this, arguments); }; };
後置裝飾:
/* 讓新添加的函數在原函數之後執行(後置裝飾)*/ Function.prototype.after = function(afterfn) { var _self = this; return function() { var ret = _self.apply(this, arguments); afterfn.apply(this, arguments); return ret; }; };
使用起來非常直觀:
document.getElementById = document.getElementById.before(function() { console.log(1); });
這裡有兩個細節:用 _self 閉包保存原函式,避免 this 問題;用 apply(this, arguments) 轉發呼叫,讓 this 與參數都原封不動地傳進去。
三、避免污染原型
直接擴充 Function.prototype 雖然方便,卻有汙染全域原型的疑慮——尤其 before、after 這類命名很容易跟函式庫或其他人的擴充撞名。改成獨立函式更安全:
var before = function(fn, beforefn) { return function() { beforefn.apply(this, arguments); return fn.apply(this, arguments); }; }; var after = function(fn, afterfn) { return function() { var ret = fn.apply(this, arguments); afterfn.apply(this, arguments); return ret; }; }; document.getElementById = before(document.getElementById, function(){ console.log(1); });
四、實例:外掛式的表單驗證
搭配《策略模式》裡的表單驗證,就能做出「驗證通過才提交」的效果。關鍵是讓前置函式回傳 false 時直接中止:
var before = function(fn, beforefn) { return function() { if(beforefn.apply(this, arguments) === false) { // beforefn返回false,直接return,不執行後面的原函數 return; } return fn.apply(this, arguments); }; };
/* 模擬數據驗證*/ var validate = function() { if(username === "") { console.log("驗證失敗!"); return false; } return true; } /* 模擬ajax提交*/ var formSubmit = function() { console.log("提交!!!"); }
username = 1; formSubmit = before(formSubmit, validate); formSubmit(); // 提交!!! username = ""; formSubmit = before(formSubmit, validate); formSubmit(); // 驗證失敗!
這正是 AOP 在實務中最常見的用途之一:日誌、權限檢查、效能計時、參數驗證,都能用同一套 before/after 掛上去,完全不碰原本的業務程式碼。
五、裝飾者模式與代理模式的異同
相同點:兩者都為物件提供某種程度的間接參照,實作上都保留了對另一個物件的引用,並把請求轉發給它。
差異:
一句話記法:代理是「控制存取」,裝飾者是「擴充行為」。希望這次的整理對大家學習 JavaScript 設計模式有所幫助。