Search code examples
javascriptbackbone.jsmemory-leaks

Could using 'self' inside a closure lead to a memory leak?


If I have a function within an object (a Backbone model in my case)...

doIt: function () {
    var self = this,  
        result = null;

    this.doMagic(function(){
        result = self.doWizardry();
    });    

    self = null;

    return result
}

...do I need to set self as null as I've done here, in order to avoid memory leaks?

Bonus question, will the closure's reference to 'result' cause a memory leak too?

Any advice on improving the efficiency of this type of structure would be much appreciated!

(Hopefully obvious that this is not a real function, just illustrative)

Thanks!


Solution

  • No. In fact, setting self to null before this.doMamgic() is called will also ruin the variable self such that this.doMagic() won't be able to use it because its value will have been cleared when this.doMagic() is actually trying to use it some time later.

    Self references in Javascript do not by themselves lead to memory leaks. The GC is smart enough to detect that. If a whole object is unreachable by other JS, it doesn't matter how many references the object has to itself inside the object.

    I see no particular reason in this code why using the variable self would lead to a memory leak and doing something like this is a well-established pattern for storing state that a callback can use (just like you're trying to do).


    As for general advice, the point of the doIt() function looks like it has issues. You appear to be trying to return the result value that was set by this.doMagic(), but this.doMagic() is not called while doIt() is executing, thus result will NEVER have a value when doIt() returns.

    So, this whole structure appears flawed. To know what to recommend would require understand what you're trying to accomplish and how you are calling/using this code which you have not disclosed.