幾年前我在社群裡隨手寫了一句「我喜歡返回函數的函數」,回覆幾乎全是問號。但對工程師來說,理解並善用這個模式是件重要的事——它能大幅削減重複代碼,也能讓你對 JavaScript 的閉包與作用域有更深的體會。
假設有個對象,底下兩個子對象各自有一個 get 方法,邏輯幾乎相同,只有屬性名稱不同:
var accessors = {
sortable: {
get: function () {
return typeof this.getAttribute('sortable') != 'undefined';
}
},
droppable: {
get: function () {
return typeof this.getAttribute('droppable') != 'undefined';
}
}
};
重複是壞味道的開始。新增第三個屬性時,你又得複製貼上一次。
function getAttribute(attr) {
return typeof this.getAttribute(attr) != 'undefined';
}
var accessors = {
sortable: { get: function () { return getAttribute('sortable'); } },
droppable: { get: function () { return getAttribute('droppable'); } }
};
好一些了,重複邏輯集中在一處。但每個 get 仍然是一個多餘的包裹層——它存在的唯一目的就是在被呼叫時把 attr 補上去。
function generateGetMethod(attr) {
return function () {
return typeof this.getAttribute(attr) != 'undefined';
};
}
var accessors = {
sortable: { get: generateGetMethod('sortable') },
droppable: { get: generateGetMethod('droppable') }
};
這就是「返回函數的函數」。generateGetMethod 被呼叫時不回傳結果,而是回傳一個已經把 attr 閉包在內的新函數。這個新函數被呼叫時的行為,與最開頭那些手寫的 get 完全一致:
// 與最初版本等效
var accessors = {
sortable: { get: function () { return typeof this.getAttribute('sortable') != 'undefined'; } },
droppable: { get: function () { return typeof this.getAttribute('droppable') != 'undefined'; } }
};
差別在於:新增屬性時不必再複製貼上函數體,只要多一行 generateGetMethod('新屬性名')。而且因為回傳的函數是一般函數(非箭頭函數),呼叫時的 this 依然正確指向調用它的對象,this.getAttribute 照常運作。
當你發現自己在寫「一堆結構相同、只有某個參數不同」的函數時,就是它上場的訊號。常見場景包括:
要注意的是,閉包會讓被引用的變數無法被回收,若在迴圈中大量產生閉包又長期持有,需留意記憶體。整體而言,這是個用一行程式碼換掉十行重複的好交易——前提是命名清楚,讓讀者一眼看出「這是在產生函數」。