js链式调用 发表于 2018-06-19 | 分类于 javascript | 阅读次数: 链式调用实现加减乘除12345678910class utils { chain(a) {this.val = a;return this;} add(b) {this.val += b;return this;} sub(c) {this.val -= c;return this;} mult(d){this.val *= d;return this;} divi(e){this.val /= e;return this;} value() {return this.val;}}let util = new utils();console.log(util.chain(1).add(2).sub(1).mult(2).divi(2).value()); //2 链式调用实现不定参相加12345678910111213function add(x) { var sum = x; var tmp = function (y) { sum = sum + y; return tmp; }; tmp.toString = function () { return sum; }; return tmp;}console.log(add(1)(2)(3)); //6console.log(add(1)(2)(3)(4)); //10 柯里化实现链式相加1234567891011121314151617181920212223function add() { var [arrayArguments,args] = [[],'']; //拼接参数数组,获取第一个参数 //将类数组参数转化为数组 args = Array.prototype.slice.call(arguments); arrayArguments = arrayArguments.concat(args); var getAllArguments = function(){ //拼接参数数组 args = Array.prototype.slice.call(arguments); arrayArguments = arrayArguments.concat(args); return getAllArguments; } getAllArguments.toString = function(){ var sum = arrayArguments.reduce((pre,next)=>{ return pre+next; }) return sum } return getAllArguments;}console.log(add(1)(2)(3)); //6console.log(add(1,2)(3)); //6console.log(add(1,2,3)(4,5)(6)); //21