1

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?

2 Answers 2

1

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";
}
Sign up to request clarification or add additional context in comments.

3 Comments

pls check my words again, im refering to VariableEnvironment which is ECMA-5's concept, that' absolutely not variables... a is changing all the way in foo's execution and update the LexicalEnvironment. but once foo ends execution, a is deleted but another reference is pointing to the same address.
Thanks Naeem, but my question was more about what happens to execution context object, AKA activation object I believe, after foo() returns. Will it be freed from memory?
Noo.. It will not be freed as it is still needed
1

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.

3 Comments

doesn't really keep the copy of variable!
Could you call a = null at the closing of foo?
@NaeemShaikh, you better check the idea of VariableEnvironment and LexicalEnvironment from ECMA. here is the link: ecma-international.org/ecma-262/5.1/#sec-10.3

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.