Please ignore that this can be re-written without variables. It’s just to have a simple example.
window.onload = function() {
var a = document.body, b = function() {console.log(1)};
a.onkeydown = b;
};
I know what happens: it works. But how?
If b was a global variable, the interpreter would store a reference to it. In this example, does the interpreter store a reference to the local variable, only to replace it, with what I assume is a copy of the function, when the local variable is destroyed? Or is the reference to the local variable still stored somewhere behind the scenes, and is then re-purposed?
Functions (and other objects) are always passed by reference.
bdoes not contain the function, rather it points to it. When you assigna.onkeydown = b, you are makinga.onkeydownpoint to the same function object. Then the function ends, so the localbvariable is destroyed but the function it points to is still there – it would only be removed by the garbage collector if there were nothing else pointing it to it.