Function scoped variables are cleaned up when the variable falls out of scope. That is, when the function has exited and there are no more references to it, the variable can be cleaned up.
There are a few exceptions to this:
- Returned values from functions
- Object attributes and methods
- Callback functions and DOM events
A return value is held in your app by assigning the return value to another variable. A return value falls under the same general rules, but the variable is now in a different function or attached to the global object. Once that variable goes out of scope, it can be cleaned up.
Object Attributes And Methods
Objects with attributes and methods fall under the same rules. An object can reference another object or function by having an attribute assigned to it: myObj.foo = thatObj. In this case, any variable that you assign to the object will now live with that object. You can remove the reference from the attribute at any time, or let the object fall out of scope / reference to clean this up.
Callback functions are handed around as function pointers, or variables that are the actual function (to over-simplify things, again). When you pass a callback function somewhere, the original scope / object that had the callback may still be holding on to it. Additionally, the code that the callback was passed to may hold on to it. If the code that it was handed to is a simple function, then the reference may fall out of scope when the function exits. If the code that you handed the callback to is an event handler, though, you might have to think a little more about cleaning up the callback / event handler
DOM Events And Event Handlers
Cleaning Up After Yourself
Cleaning Up In A Backbone App
For example: events. An even handler / callback method works by having a reference between the object that triggers the event and the callback that handles the event. This is one of the easiest places to cause memory leaks in a Backbone app and I discuss it in detail in my Zombies! blog post.
Additionally, my Backbone.Marionette framework that sits on top of Backbone does a lot of cleanup work for you. I provide access to a Region object and various types of views that automatically clean up DOM references, child-view references, event handler references, etc.
There’s More To It…
For example, don’t define functions inside of object constructors unless you absolutely have to. Doing this will create a new copy of the function every time you instantiate an object. Instead, attach functions to the object prototype. This will reduce the overall memory footprint of an application, reduce the amount of work that the garbage collector has to do, and generally improve your application performance.
There’s more to it, still. If you’re interested in getting all the detail, check out some of these resources:
- Annotated ECMAScript 5
Post Footer automatically generated by Add Post Footer Plugin for wordpress.