Can someone explain this Javascript closure exampl

2019-03-05 02:22发布

问题:

function makeAdder(x) {
    return function(y) {
        console.log("X:" + x + " Y:" + y);
        return x + y;
  };

}

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

console.log(add5(2));
console.log(add10(2));

Ok, I am a bit confused with this example on developer.mozilla under closures.

If someone can explain with as much detail as possible in order for me to get my head around closures.

Ignore the console.log, I just added that to see what values are displayed and from that I can see that x is 5 and y is 2 when you execute add5 for example.

I consoled add5() to see what I get and I got NaN - and I am guessing that is because I have not specified an argument because it wants one and can't add a number to undefined.

So the confusion is that argument y in madeAdder's inner function.

Hope someone can provide a much better explanation than mozilla...i think the clue is environments but I'm new to this so need help from experts.

Thanks

回答1:

function makeAdder(x) {
    return function(y) {
        console.log("X:" + x + " Y:" + y);
        return x + y;
    };
}

makeAdder required one parameter called x and returns a new function requiring the parameter y. When executing this inner function, the x of the outer scope will be added to the parameter y and the sum is returned.

var add5 = makeAdder(5); will create a new instance of the inner function and store it to add5. x for this inner function is set to 5. when executing add5 with add5(2) this will return 7, because the x value ( outer scope 5 ) will be added to the parameter 2.

The procedure for add10 is equaly.

Edit when not passing a parameter ( either inner or outer function or both ) the parameter ( y or x or both ) will be undefined. undefined+number or undefined+undefined returns NaN because one or more of the summand is not a number.

Edit 2: Procedure Walkthrough:

var add5 = makeAdder(5); will set add5 to:

function(y) {
   console.log("X:" + 5 + " Y:" + y);
   return 5 + y;
}

Because makeAdder(5) returns its inner function and sets x to 5. So when now executed with var sum = add5(2); this generated function will calculate and return 5 + y (5 + 2).

Note: it's not really setting x to 5 ( instead its still a reference to the outer x ) but i think this is easier to understand and does not change anything in this particular example