在 Web 前端筆試中,常遇到這樣一道題目:實現一個函數 func,使其支持鏈式調用 func(1)(2)(5)...,並最終返回所有括號中數值的乘積。這考察的是 JavaScript 函數柯里化、閉包以及 this 指向的理解。
利用函數返回自身引用,並在函數屬性上累積乘積。每次調用傳入參數時,更新累積值;當不傳參數(或傳入 undefined)時,返回最終結果。
function func(a) {
if (typeof a === 'undefined') {
return this.result;
} else {
this.result = (typeof this.result === 'undefined' ? a : this.result * a);
return func;
}
}
// 使用示例
var r = func(1)(2)(5)(); // 返回 10
console.log(r); // 10
func,所以 this 指向同一個函數對象,屬性得以保留。return func 使鏈式調用得以繼續。const func = (a) => {
if (a === undefined) return func.result;
func.result = (func.result === undefined ? a : func.result * a);
return func;
};
這種模式在函數式編程中稱為「柯里化」,常用於構建流式 API 或延遲計算場景。