The closure feature is widely used in JavaScript and make it quite difficult for programmer who was used to program in a no-closure language. So what is the best practice about using closure and how to avoid shooting yourself in the foot.
-
5You can shoot yourself in the foot with them? I can see how they can be hard to grasp, but if you understood them properly (e.g. realize that they capture a variable, and reflect later changes to that variable, including what happens if you capture an iteration variable), there's little that can go really wrong.– user7043Apr 28, 2011 at 13:18
3 Answers
In my opinion, the best way to avoid shooting yourself in the foot with a cool language feature is don't use it if you don't need it.
Find out what closures can do for you and how they are commonly used and stick with standard patterns unless you really need (not want) to use them for something else.
If you just want to use them (for instance, to learn them), do it on your own play project.
Understand what a closure is
- A closure is a first class function which captures lexical bindings in it's environment. This prevents the garbage collector from free'ing the space until all references to the closure are gone.
Understand how the closure will grow
- You can easily create a memory leak with a closure because the only interface to the allocated memory is through the closure (typically). You should make sure your closure will not grow unbounded.
Watch out for capturing references
- This is more of standard gotcha, but it's even more important when dealing with closures. A closure will capture lexical variables including ones that contain references. This means whatever those references point to will continue stick around as long as the closure is around, unless they are explicitly weak refs.
Don't close over variables you don't need to close over
- It's wasteful, bad code and makes it more likely you'll introduce a memory leak.
Make the functions that will become closures as simple as possible
- The bigger, more complex the function that will become a closure, the more likely you are to have a bug which may lead to a memory leak.
Don't create closures when they aren't needed
- See: common sense
In general, you can avoid shooting yourself in the foot by:
- Fully understanding scope and execution context of the closure contents
- Understanding how values and object references behave when closed over
- Understanding exactly when things in the closure are evaluated, especially for cases like using the this keyword or an eval statement in the closure (i.e. closure creation time vs execution time)
Play around with closures, figure out how they work, then you can use them confidently and get expected results.