JS closures, how the circuit comes out of this result?

function makeAdder(x) {

 return function(y) {
 return x + y;
};
};

var add5 = makeAdder(5);
var add10 = makeAdder(10);

console.log(add5(2)); // 7
console.log(add10(2)); // 12
Hello! Not clear example circuit in this code ..


What comes out as 7 and 12 ? Can someone explain Flow of this function ?
July 2nd 19 at 18:13
4 answers
July 2nd 19 at 18:15
Solution
July 2nd 19 at 18:17
Solution
Your code is equivalent to this:
function makeAdder() {
 var x=arguments[0];
 return function() {
 var y=arguments[0];
 return x + y;
};

};


Further, when you call makeAdder(5), the variable add5 becomes a reference to the function function(y) {
return x + y;
};
And this function keeps values from the parent scope, i.e. the variable x
Accordingly, when you vyzyvaet add5(2) in return x + y; you have substituted the values 5 and 2 respectively.
That's all.
Just do not understand the hidden processes that occur in this algorithm .. Theoretically about scope is clear.. But one moment I want you to clarify.. the first time you call makeAdder(5) creates the object from a local environment variable , when you call makeAdder(10) creates one object with the local variable environment (for each call to your object ? ). Then as was vernut the function itself var var add5 and add10 contain links to your own created object, which contains an external variable and a function that has access to this variable and then when you call add5 and add10 called the internal function of each object with its local variable ? Somehow so yeah .. tell me pliz... (brains explode=))!! - stephon_Abshire commented on July 2nd 19 at 18:20
: yeah, absolutely. - Emilie_OKee commented on July 2nd 19 at 18:23
July 2nd 19 at 18:19
when an object X is stored inside scope return funtion. then you call the second function in which X is known, and comes as an option.
July 2nd 19 at 18:21
The call to makeAdder returns a object-the function to where you saved the environment in the form of the variable H.
Then you make a call to this object-function add5(2) with parameter y.

Find more questions by tags JavaScript