Home > Net >  Does anonymous functions prevent variables from being destroyed by the garbage collector?
Does anonymous functions prevent variables from being destroyed by the garbage collector?

Time:10-10

I will be using this HTML and JS DOM script as an example, to explain the problem:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title></title>
</head>
<body>

    <button id="my-button">Do Something</button>
    <script type="text/javascript">
        let setButtonFunc;

        setButtonFunc = function() {
            let button = document.getElementById("my-button");
            let phrase = "Printing Something";

            button.onclick = function() {
                text = document.createTextNode(phrase);
                document.body.append(text);
            }
        }
        setButtonFunc();
        
        setButtonFunc = null;
    </script>

</body>
</html>

I defined a function setButtonFunc into a variable created with the let keyword. This function is used to set the button's onclick property, enabling it to append text to the page every time its pressed.

My question is: will the variables phrase and button be collected by the Garbage Collector, once the variable setButtonFunc is set to null?

Logically, all their refereces vanish from that line. Once the variable is set to null, only the button's onclick function should remain in memory. All the other variables should be collected by the garbage collector, as there are no other references to keep them alive out of scope.

However, if you keep pressing the button, the onclick function will keep executing normally as if phrase was never released from memory.

I just can't seem to understand it. In python for example, if I were to execute this same example, there would be a time when the garbage collector would destroy the variable and an Exception would be raised.

Why doesn't it happen here with Javascript? Is the anonymous function (used on button's onclick) holding their references somehow? Am I missing something from the documentation?

CodePudding user response:

Is the anonymous function (used on button's onclick) holding their references somehow?

This is exactly what is happening and it is called hoisting

CodePudding user response:

button variable should get collected but phrase is still referenced inside click event handler so it will be kept alive as long as the click handler is alive

  • Related