Simplify Scope with Javascript Closures
Posted by Maciek Mon, 25 Sep 2006 20:25:09 GMT
For those of you using Javascript prototypes as classes and interacting them with HTML or DOM elements, it’s often tricky or painful to keep things clean and nicely separated. Often, the result is a bunch of global (i.e. members of window) variables littered all over the place. Still more difficult is the problem of somehow associating given DOM objects with given class (or prototype) instances without having to use clumsy proxies or tracking keys in hashes.. etc. You can greatly simplify this sort of code by using closures. In the following article, I will give you a simple pattern to apply to any functionality you want to attach to objects that steal or would otherwise confuse scope. This pattern is useful anywhere you attach functions to the properties of objects outside of those functions’ context: AJAX XMLHttpRequest objects, DOM elements, or your own prototype-derived objects..
Read more...






