DWQA QuestionsCategory: ProgramOn JS garbage collection
Aiello_Chan asked 1 month ago

Code says everything
Core code
On JS garbage collection
Q:

  1. Will my new object be recycled?
  2. If it will not be recycled, is there any other way to recycle the object except for the following methods:
var a = new A();
a = null;

Attach complete runnable Code:

<!DOCTYPE html>
<html>

<head>
    <style>
        .div {
            width: 160px;
            box-shadow: 0 1px 2px rgba(0, 0, 0, .6);
        }
    </style>
</head>

<body>
    <div class="div">
        <h1>
            Click ME!
        </h1>
    </div>
    <script></script>
    <script>
        function A() {
            this.addListener = function () {
                $('.div').on('click', function () {
                    alert('Clicked Me!');
                });
            }
        }

        (new A()).addListener();
</script>
</body>

</html>
2 Answers
Best Answer
idollo answered 1 month ago
  1. Your write a will clean up from memory unless you call the a instance in the event binding callback method
  2. Remove the. Div from the DOM tree, because the event is bound, so the DOM memory will not be cleared
    Of course, if it is jquery-1.3. X or above

$(ELM). Remove() / / this method moves the event binding
Because the method executes at the same time:
jQuery.event.remove(elm);
Therefore, if the DOM is removed with $(ELM). Remove(), it will be recycled
But if there is a UL, there are n Li in it, all of which are bound with events
When $(“UL”). HTML (”) / / clears UL with this method, Li will not be recycled
So, recycle or not. It depends on how you use it
In addition, there are global DOM references, which are not clear. It depends on the life cycle of your DOM variables, such as:

var $div = $('<div>hello</div>');
//Add to body
$div.appendTo("body");

// remove
$div.remove();

//$div hasn't been recycled because I can still:
$div.appendto ("body"); // added to body again

// ...
//If $div is in a function closure and is not referenced later, remove() will recycle
//If $div is in a global environment, such as window. $div, it will never be recycled
Aiello_Chan answered 1 month ago

Let’s answer one to ourselves first. After thinking about it, it’s actually a closure.
However, there is a new problem. If I directly use the following method to empty the instantiated object and delete the DOM object, but do not release the event listener, will this object be recycled?

var a = A();
a.addListener();
a = null;
/*Code to remove. Div from dom*/
theWalker replied 1 month ago

Can’t