This is my code :
var markers={};
example();
function example() {
var myFunct = function () {
alert("hello");
};
markers["myIndex"] = myFunct;
}
markers["myIndex"]();
as you can see, myFunct is “var” (so, when example() finish, it will be destroyed, because it is local). But in fact, accessing to markers["myIndex"](), the function is referenced, and I can access to it. Why?
In JavaScript, functions are objects just like other objects. When you do this:
…you’re creating a function and assigning a reference to that function to the variable
myFunct. Then when you do this:…you’re assigning another reference to that function to
markers["myIndex"]. So regardless of anything else that might happen to themyFunctvariable, becausemarkers["myIndex"]still has a reference to the function, the function is kept in memory.But separately, there’s a more subtle misunderstanding in your question as well: You’ve said:
That’s not true in JavaScript. In JavaScript, local variables are actually properties of a hidden object, called (deep breath) the variable binding object of the execution context (let’s just call it the “variable object”). This object is associated with the particular call to
example: It’s created when the call toexampleis executed. Now, in the normal course of things, whenexamplereturns, if nothing has any outstanding reference to the variable object, then you’re quite correct that it is eligible for garbage collection. But in your case, something does have a reference to the variable object: The function you created. When you create a function, it receives an implicit reference to the variable object for the context in which it was created, and it keeps that reference for as long as the function exists. So even though the function you’re creating doesn’t refer to anything in the variable object for the call toexample, it has that reference to it nevertheless, and the variable object cannot be reclaimed until or unless nothing has a reference to the function anymore. This is how closures work. The foregoing text notwithstanding, closures are not complicated, they’re really, really simple when you understand how they work.(I’ll just note here that some JavaScript engines introspect the code sufficiently that they can reclaim variable objects even when there are outstanding closures that refer to them. Specifically, if the closures [functions] don’t actually use any of the variable object’s properties, and they don’t use
eval, then the engine may be able to release the variable object. Chrome’s V8 engine does this, for instance. But that’s a runtime optimization; the concept is as described above.)