scope calling functions inside functions

后端 未结 5 1655
既然无缘
既然无缘 2021-02-04 01:23

Hope somebody finds the time to explain little about functions in functions and scoping. I am trying to understand little more on functions and scope of variables and found a qu

5条回答
  •  不要未来只要你来
    2021-02-04 01:41

    1. Line 01-13 defines the function sum within the global scope.
    2. Line 15 calls sum and changes scope to inside the function.
      1. The variables a and sum and the closure function f are all defined in the function's scope - with the sum variable hiding the function definition from the global scope.
      2. I'll skip over the toString bit here as its not important till later (when it gets very important).
      3. The function sum finally returns a reference to the closure function f to the global scope as an anonymous function (since f can only be referenced by name from within its containing function's scope).
    3. Back to line 15 - sum(1)(2) is the same as (sum(1))(2) and since sum(1) returns f then this can be reduced to (f)(2) or, more simply, f(2).
      1. Calling f(2) adds 2 to sum - sum is defined in two scopes: as a function in the global scope; and as a variable (currently assigned the value of 1) within that function which hides the definition from the global scope - so, in f, the sum variable is set to 1+2=3.
      2. Finally, in f, the function returns itself.
    4. Back, again, to line 15 - f(2) returns f (although the named function f cannot be referenced in the global scope and, again , is treated as an anonymous function)
    5. alert() is processed and the anonymous function (referred to as f) is converted to a string to be alerted; normally when alert() is called on a function it will display the source for the function (try commenting out Line 10 to see this). However, since f has a toString method (Line 10) then this is invoked and the value of sum (as defined in the function containing f) is returned and 3 is alerted.

提交回复
热议问题