Syntax of Closures

前端 未结 3 1957
我在风中等你
我在风中等你 2021-01-19 04:28
function makeIncreaseByFunction(increaseByAmount) {
  return function (numberToIncrease) {
    return numberToIncrease + increaseByAmount;
  };
}

makeIncreaseByFunc         


        
3条回答
  •  囚心锁ツ
    2021-01-19 05:10

    makeIncreaseByFunction(3) would return function so the syntax for then calling it with 10 would be makeIncreaseByFunction(3)(10).

    This is easy to understand as if you have a function foo (imagine that the return of makeIncreaseByFunction(3) is such a function, they are evaluated identically), you would then call it with 10 using foo(10).

    As for how the value of 10 is being 'passed', this is the wrong way to thing about things.

    You must realise that in Javascript functions are first class objects. Instead of passing the value to the inner function, you are creating a function that does what you want and then calling it with the outer argument.

    It is the same as using a variable to add within a function in a non-functional language except functions can be dynamically created at runtime and the values of any variable in their definition can be set influencing their internal consistency.

    The closure refers to the fact that the created function is a black-box which hides the variable used to initialize it, despite still using that variable to increment the value it is called with.

提交回复
热议问题