ramaralo
ramaralo

Reputation: 1031

Declare vars inside javascript function and memory management

For some time I've had a doubt about js potential memory leak in this type code:

function foo() {

    var a = "This is my content";

    $('#myElemId').on('click', function() {

        $(this).html(a);

    });
}

My question is:

When foo is called, I suppose it is created an execution object, allocates memory for var a and assigns an event listener to a dom element. Once foo returns it should free the execution object but I think it won't because there is still a reference to var a from the click listener, right?

Upvotes: 1

Views: 55

Answers (2)

Naeem Shaikh
Naeem Shaikh

Reputation: 15715

you are right. variables will be only freed if it is no longer needed.

In your case the variable a is still needed for the event callback so it is not deallocated. It still exists,

As another answer for this post by elaijuh says,It is a copy of real variable, actually it is not the copy stored in the event callback function.

You can see this fiddle http://jsfiddle.net/3y7qbjav/ , so still you can change the value of var a after binding the click event. So the variable is not freed.

function foo() {

    var a = "This is my content";

    $('#myElemId').on('click', function() {

        $(this).html(a);

    });
    a="new content after the event binding";
}

Upvotes: 1

hjl
hjl

Reputation: 2802

it's a typical closure issue. actually the anonymous function will keep a copy of foo's VariableEnvironment but not a. so when foo ennds execution, it's execution context is destroyed as well as a. the anonymous function can still refer to a via it's scope chain.

Upvotes: 1

Related Questions