What happens when a local variable is assigned to a global object?

Please ignore that this can be rewritten without variables. This is just a simple example.

window.onload = function() {
    var a = document.body, b = function() {console.log(1)};
    a.onkeydown = b;
};

      

I know what's going on: it works. But how?

If b

is a global variable, the interpreter will keep a reference to it. In this example, the interpreter stores a reference to the local variable, just for replacement, with what I assume is a copy of the function when the local variable is destroyed? Or is it a reference to a local variable that is still stored somewhere behind the scenes and then reassigned?

+3


source to share


1 answer


Functions (and other objects) are always passed by reference. b

does not contain a function, but points to it. When you assign a.onkeydown = b

, you are doing a.onkeydown

functions for the same object. The function then ends, so the local variable is b

destroyed, but the function it points to still exists - it is only removed by the garbage collector if nothing else points to it.



+4


source







All Articles