编写函数 实现如下结果
sum(1, 2, 3).valueOf() // 6 sum(1, 2, 3)(4).valueOf() // 6 sum(1, 1, 3)(1, 2, 3)(100).valueOf() // 111
代码如下
1.使用了闭包
let sum = (function () { let count = 0 return function fn() { let args = [].slice.call(arguments) count = args.reduce((a, b) => a + b, count) fn.valueOf = function () { console.log(count) count = 0 } return fn } })()
2.
let sum = function () { sum.count = (sum.count || 0) sum.count = [].slice.call(arguments).reduce((a, b) => a + b, sum.count) sum.valueOf = function () { console.log(sum.count) sum.count = 0 } return sum }