开发者

When should I use the destroy method?

I made a small javascript framework designed to add some useful stuff in the prototyped object model (super method call, inheritance, auto init...).

In this framework, some object methods are automatically called, like "init" to construct the object and "destroy" on window unload.

I have two questions about this destroy method :

  • What is this method used for?

I think it should do some cleaning on DOM objects (unbind events), but is there other cleaning to do?

  • Should this method be called on another event? Is it possible to detect when an object is destroyed and call this method at this time?开发者_运维问答

If anyone is interested in this framework, I posted it on gitHub, but right now there's no documentation :-/ : https://github.com/LeMisterV/EasyPrototype


A better question, why do you need to destroy anything? if the window is unloading, everything will be garbage collected on your behalf.


Some versions of Internet Explorer get stuck on circular references between JavaScript and the DOM, since they are garbage collected separately. This tends to be an issue when you start adding event handlers to everything.

What you should do in your framework is keep track of every time you add an event so that you can go through that array of events and destroy each of them on unload.


First, and foremost, the reason for a "destroy" (or any destructor) is to bring your "system" or program into a known stable state. In browsers, all memory usage (which is the classic issue) is automatically done for you with Garbage Collection.

So the only reason left why you might want a destructor ("destroy" method) is if there are abstract properties about your system that the object needs to ensure is in a known state.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜