If I have a JavaScript constructor function, and I set a destroy method on its prototype. Is it possible to delete (or at least unset) the instance from the destroy method? Here’s an example of what I’m trying to do.
Klass.prototype = {
init: function() {
// do stuff
},
destroy: function() {
// delete the instance
}
};
k = new Klass
k.destroy()
console.log(k) // I want this to be undefined
I understand that I can’t simply do this = undefined from with the destroy method, but I thought I could get around that by using a timeout like so:
destroy: function() {
var self = this;
setTimeout( function() {
self = undefined
}, 0)
}
I thought the timeout function would have access to the instance via self from the closure (and it does), but that doesn’t seem to work. If I console.log(self) from inside that function it shows up as undefined, but k in the global scope is still an instance of Klass.
Does anyone know how to make this work?
kis a reference that points out to an instance ofKlass. when you calldestroyas a method ofKlassthethisinside the function gets bound to the object you called adestroymethod on. It now is another reference to that instance ofKlass. Theselfthat you close on in that little closure is yet another reference to that instance. When you set it toundefinedyou clear that reference, not the instance behind it. You can’t reallydestroythat instance per se. You can forget about it (set all the references toundefinedand you won’t find it again) but that is as far as you can go.That said, tell us what you want to accomplish with this and we’ll be glad to help you find a solution.