Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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.

share|improve this question
    
Why are you trying to do this? –  Lee Taylor May 16 '13 at 12:15
    
Is this an attempt to implement the singleton pattern? –  basilikum May 16 '13 at 12:21
    
no. it won't be a singleton. –  zsitro May 16 '13 at 12:25

2 Answers 2

up vote 1 down vote accepted

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).

share|improve this answer
1  
It's even worse actually: delete has no effect on variables (see MDN). –  tom May 16 '13 at 12:32
    
ahh, I see.. The problem is that the instance won't have any named references as in my example. –  zsitro May 16 '13 at 12:32
    
Next time I'll use factory pattern where I can abort instantiation.. –  zsitro May 16 '13 at 12:37

Have you tried something like this?

function myFunction() {
    // do the actions
    delete myFunction;
};

myFunction();
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.