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?
No. this is just a local reference to the object so deleting it does not make the object not exist. There is no way for an object to self destruct in this manner.
instance = new Class(); //since 'storage. instance' is your only reference to the object, whenever you wanted to destroy do this: storage. instance = null; // OR delete storage.
That means all the objects in JavaScript, inherit the properties and methods from Object. prototype. This is called Prototype chaining. This is a very powerful and potentially dangerous mechanism to override or extend object behavior. Objects created using new keyword, inherit from a prototype called Object.
Every object in JavaScript has a built-in property, which is called its prototype. The prototype is itself an object, so the prototype will have its own prototype, making what's called a prototype chain. The chain ends when we reach a prototype that has null for its own prototype.
k
is a reference that points out to an instance of Klass
. when you call destroy
as a method of Klass
the this
inside the function gets bound to the object you called a destroy
method on. It now is another reference to that instance of Klass
. The self
that you close on in that little closure is yet another reference to that instance. When you set it to undefined
you clear that reference, not the instance behind it. You can't really destroy
that instance per se. You can forget about it (set all the references to undefined
and 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.
Though deleting its own object instance is possible, it is very tacky. You might want to check out this article.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With