Clear object memory in javascript

1.6k views Asked by At

I am using General Interface in my web application and I have javascript classes and methods to create objects for my classes. I would like to clear the memory when the objects are not used. My question is how can I clear the object's memory.

I have tried with 'obj = null;' and 'delete obj;'. Both are not working as expected.

Is there way to clear the object and object memory in JavaScript or in General Interface.

-Sridhar

3

There are 3 answers

0
amelia On BEST ANSWER

You can't. As long as every reference is really removed (e.g. setting to null as many have suggested), it's entirely up to the GC as to when it'll run and when it'll collect them.

0
Sunil Dodiya On

try to set to null.

var a = new className();
alert(a);

a = null;
alert(a);
1
Ikrom On

You can use Self-Invoking Functions

Self-invoking functions are functions who execute immediately, and create their own closure. Take a look at this:

(function () {
    var dog = "German Shepherd";
    alert(dog);
})();
alert(dog); // Returns undefined

so the dog variable was only available within that context

EDIT
If memory leak is related to DOM, here written how to manage it. So, i tried to solve like that:

var obj = {};//your big js object
//do something with it

function clear() {
    var that = this;
    for (var i in that) {
        clear.call(that[i]);
        that[i] = null;
    }
}

clear.call(obj);//clear it's all properties
obj = null;