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
sum
within the global scope.sum
and changes scope to inside the function.
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.toString
bit here as its not important till later (when it gets very important).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).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)
.
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
.f
, the function returns itself.f(2)
returns f
(although the named function f
cannot be referenced in the global scope and, again , is treated as an anonymous function)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.