Reputation: 1892
I tried to create a method which can delete itself while instantiating.
After several failed attempt I ended up writing this evil rem()
var g = function () {
this.rem = function () {
var _instance = this;
setTimeout(function () {
console.log('_instance before:', _instance, 'scope:', this);
delete _instance;
console.log('_instance after:', _instance);
}, 10);
return this;
};
return this;
}
I know it looks ugly. But it's a bit strange for me that this not working either. Inside the anonymous function the scope is window
and the _instance
variable is seems to be referring to the desired instance as well.
var t = new g();
t.rem();
outputs:
_instance before: g {asdf: 3, rem: function}, scope: Window {top: Window, window: Window, location: Location, external: Object, chrome: Object…}
_instance after: g {asdf: 3, rem: function}
What is the reason it is not working?
Thanks.
Upvotes: 1
Views: 1656
Reputation: 1734
Your approach won't work, unfortunately. When you delete _instance you are deleting a reference to the object, not the object itself. There is still another reference to the same object (t) and so the object will not be garbage collected by the browser. Instead of t.rem();
you should just use t = null;
and the browser will get rid of the object in due course (assuming there are no other references to it).
Upvotes: 1
Reputation: 11731
Have you tried something like this?
function myFunction() {
// do the actions
delete myFunction;
};
myFunction();
Upvotes: 1