console.log(sum(1)(2)(3)); // -> 6
console.log(sum(3)(15)); // -> 18
function sum(a) {
let currentSum = a;
function f(b) {
currentSum += b;
return f;
}
f.toString = function() {
return currentSum;
};
return f;
}
This function adds the arguments that are passed to it, and after all additions the string currentSum is returned. I don’t really understand how the conversion to a primitive occurs and why write it through a function
2
Answers
The default
toString
function of a Function will return the stringified function. To display the (intermediate, enclosed)currentSum
value off
, you need to override thattoString
function. Maybe this snippet clarifies this:For fun: because a
Function
is just anotherObject
, you can also extend it with your own ‘value’ method. In that case you have to explicitly call the extension method(s) to retrieve the enclosed value.One step further may be to convert the methods to getters (so you don’t need parentheses using them), or add your own setters to the function:
Q&R:
-1- what is
sum()
?in JS everything is an Object (even if they are defined as a function).
-2- what is
currentSum
?it is a local value inside
sum()
.this local value can only be changed inside the scope of
sum()
.-3- what is
f
?an object function which add his argument value to
currentSum
and return itself (a function)
-4- what is
f.toString
?it is an overloading method on the
f
objectit overload the deault
Object.prototype.toString()
(javascript is a prototype object model)-5- what happend in
console.log(sum(1)(2)(3));
?there is differents step :
__a)
let fctA = sum(1)
-> currentSum = 1, andreturn f
see sum()’s last line__b)
let fctB = fctA(2)
-> currentSum += 2 andreturn f
__c)
let fctC = fctA(3)
-> currentSum += 3 andreturn f
__d)
let D = fctC.toString()
=> call thetoString()
method off
.