Search code examples
javascriptmodel-view-controllerobjectprototypal

How to delete an object in Javascript crossbrowser


var obj = {
    destroy: function(){this = null;}
};

obj.destroy();

This works in Chrome, however firefox is throwing an error referencing this for some reason. Is there a better way to kill this object within a method?

Error:

invalid assignment left-hand side
[Break On This Error] destroy: function(){this = null;} 

Solution

  • Not sure why Chrome allows for it but you can't assign a value to this. You can reference this, but you can't assign a value to it.

    If you have some array destruction you want to perform you can reference this.myArrayName within your destroy method and free up whatever you're trying to release, but you can't just assign null to this to destroy an instance.

    I suppose you could try something like this:

    var foo = {
        // will nullify all properties/methods of foo on dispose
        dispose: function () { for (var key in this) this[key] = null; }
    }
    
    foo.dispose();
    

    Pretty much as close as you can get to legally nullifying "this"...

    Happy coding.

    B