Can anyone please explain this code? This example is taken from javascript.info.
I don’t understand, especially the f.toString = function(){ return sum} part.
function sum(a) {
var sum = a
function f(b) {
sum += b
return f
}
f.toString = function() { return sum }
return f
}
alert( sum(1)(2) ) // 3
alert( sum(5)(-1)(2) ) // 6
alert( sum(6)(-1)(-2)(-3) ) // 0
alert( sum(0)(1)(2)(3)(4)(5) ) // 15
I think the author of that snippet wanted to achieve one goal, that is, something like “faking” operator overloading which is possible in other languages.
Since
sumreturns a function reference, we could not go likeThat would result in something weird like
"function sum() { ... }5". That is because ECMAscript calls the.toString()method on objects when invoked in a Math operation. But since he overwrites the.toString()method returningsum(which is a number), it does work again.