There is some serious ninjitsu in this article. Here’s are some of the tricks and pointers that I found most interesting:
- Branch Functions: You can define a function that conditionally returns a slimmed-down function. This keeps the conditional logic in the initial call, while still giving you code reuse wherever you decide to use a closure.
- Bridges: When you’re developing an API that others need to use (or that you need to write tests against), adding bridge functions can keep the interface clean. The example given was a click handler, where the handler function is handed its parameters directly instead of assuming a certain scope. The bridge function then handles that dependency.
- Event Delegation: The classic example is an unordered list where you want every item to have a click handler. Instead of assigning one to each item, catch the event as it bubbles up and have just one handler on the whole list that uses
event.targetto decide what to do.
- Include Methods with your getElementsByWhatever: Write your own get function so that you can pass a callback in. That way, you can perform an action on each without looping twice.
- Encapsulate your Code: Use closures to keep cruft out of variable scope. See Crawford’s talks (below) for neat ways to simulate private, protected, public, etc. “methods” and properties using closures.
Using Prototype at Instructables has made me a bit lazy, since the framework does so much for me. It’s good to get back deep into the language, every so often. A little fiber for the mental digestive tract.