Does the interpreter keep a hidden reference to the function in the background, or does the interpreter somehow inline the function?
This can not be answered globally for all javascript engines. But the parser will most likely have to keep a reference to your function a
for both the anonymous functions you define on document.onclick
and document.onkeyup
. So a
is not destroyed right away, it is only inaccessible through the restrictions of the javascript variable scope.
This is why closures can lead to memory leaks, because it is hard for the engine to actually dereference a
properly. (which was a problem with the IE engine and still is when not handled carefully). And since you can not dereference a
manually, because you have no access to the variable, there are no quick fixes to memory leaks arising from this type of pattern.
Your example is also not a closure, since it does not return a function, but it deals with the same kind of variable scope problems, since it references a local variable a
inside functions not sharing the same scope (document.onclick
and document.onkeyup
).
I highly suspect that no engine will try to inline the function a
, since that would unnecessarily duplicate the function object. It is most likely kept with a pointer
and the mentioned reference count to be allowed to be destroyed easily once the reference count is down to 0 (in your example, when document.onclick
and document.onkeyup
are dereferenced (set to null
or undefined
).
Is this type of code to avoid a global variable efficient?
It is always good to avoid global variables, so in general: yes, it is an efficient way to avoid global variables. Every good engine should also destroy a
once document.onclick
and document.onkeyup
are dereferenced.