Question

In JavaScript, I have complex objects comprising functions, variables and closures.

These objects are very large, very complex and created and destroyed over and over again. I will be working on a very low-powered, very low-memory device, so it's important to me that when the objects are deleted that they are really gone.

Here's a code example:

window["obj"] = {};
obj.fun1 = function(){
    console.log(1);
};

(function(){
    var n = 2;
    function fun(){
        console.log(n);
    }
    obj.fun2 = fun;
})();

(function(){
    var w = "Three";
    function fun(){
        console.log(w);
    }
    obj.fun3 = fun;
})();

(function(){
    var w = "f.o.u.r.";
    function fun(){
        setInterval(function(){
            console.log(w);
        }, 1e3); // e.g. a timeout
    }
    obj.fun4 = fun;
})();

obj.fun1();
obj.fun2();
obj.fun3();
obj.fun4();

var fun2 = obj.fun2;

// window.obj = null;
// window.obj = undefined;
delete window.obj;
console.log(typeof obj); // undefined

A secondary issue is the question of "lingering references", such as the following:

fun2(); // 2
// Interval: "f.o.u.r.", "f.o.u.r.", "f.o.u.r.", "f.o.u.r." ...

Is there anything that can be done about those (except a manual clean up before deleting the object)?

A JSFiddle of the code above is here: http://jsfiddle.net/8nE2f/

Was it helpful?

Solution

You will have the best effect by doing this

window.obj = null;
delete window.obj;

Setting objects to null removes any references to it. Also remember that the delete command has no effect on regular variables, only properties.

To better ensure object destruction you may consider not using the global context at all, that is usually considered as an antipattern.

OTHER TIPS

The only way to get rid of an object is for JavaScript to garbage-collect it, so making sure there really aren't any references to the object left and praying is the only way to go.

If you're repeatedly creating and destroying the same object, consider using an object pool.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top