In the definition of javascripot function closures, there is generally a outer function, a inner function. So does "closure" mean the outer function or the inner function?
From the official definition, it is not clear: a closure is a combination of a- code block and data of a-a-which this cod E block is created.
Then in the following function:
function Outerfunc (y) {
var internal1 = 100;
var internal2 = 200;
function Innerfunc1 (x) {
internal1++;
Internal2--;
}
function Innerfunc2 ()
{
internal1--;
internal2++;
}
function Get1 ()
{
return internal1;
}
function Get2 ()
{
return internal2;
}
Y.FUNC1 = INNERFUNC1;
Y.FUNC2 = INNERFUNC2;
Y.get1 = Get1;
Y.get2 = Get2;
}
Which function is the closure? is Outerfunc closure innerFunc1, Innerfunc2? Or the opposite?
The general textbook is that innerfunc1 closure of Internal1 and Internal2. The same INNERFUNC2 closures the above two variables. This is not a violation of the official definition, but always feel that the "semantic" level is not justified. Readers who have read my C + + blog will know that I am obsessed with righteousness.
I think that the right understanding should be Outerfunc, innerfunc1, Innerfunc2,get1,get2 together to form a closure that swept all the Outerfunc's free variables, parameters, and local variables.
Why, then? Because:
1 innerfunc1 and INNERFUNC2 are "defined" within Outerfunc, sharing Outerfunc's free variable internal1 and internal2. It doesn't make sense to talk about a single function alone.
2 because of the "semantics" of innerfunc1 and Innerfunc2,outerfunc, fundamental changes have taken place. Internal1 and Internal2, which were originally "auto" variables, became "heap" variables. The specific implementation is the implementation details of JavaScript. But knowing this subtle detail will deepen your understanding of JavaScript. Also know the cost of closure's implementation.
3 The above detailed interpretation: No closure of the outerfunc can be optimized, using stack variables to achieve internal1 and internal2. With closures, INTERNAL1 and Internal2 must be implemented by garbage collection. Of course, the functionality will drop dramatically.
The 2nd above is fundamental to understanding "closures" and the nature of JavaScript functions.