Can someone explain this Javascript closure example

北城余情 提交于 2019-12-02 13:31:33
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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!