1. 程式人生 > >js 鏈式

js 鏈式

[] var class function urn ole ons arguments lis

寫一個函數讓下面兩個輸出結果相同;
console.log(sum(2)(3));
console.log(sum(2,3));
var sum = (function() { var list = []; var add = function() { // 拼接數組 var args = Array.prototype.slice.call(arguments); list = list.concat(args); return add; } // 覆蓋 toString 方法 add.toString = function
() { // 計算總和 var sum = list.reduce(function(pre, next) { return pre + next; }); // 清除記錄 list.length = 0; return sum; } return add; })(); var s=sum(2, 3 ,4)(3)(1,2); console.log(s.toString()); console.log(sum(2, 3 ,4).toString()); console.log(sum(
2, 3 ,4).toString()); console.log(sum(2)(3)(4).toString()); console.log(sum(2)(3)(4).toString());

js 鏈式