Javascript Ninjahackery

If you’re into hacking Javascript, check out Dustin Diaz’ “Seven JavaScript Techniques You Should Be Using Today”.

There is some serious ninjitsu in this article. Here’s are some of the tricks and pointers that I found most interesting:

  1. 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.
  2. 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.
  3. 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.target to decide what to do.
  4. 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.
  5. 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.

If the Diaz article is about tactics, then Douglas Crawford’s Yahoo! Lectures on Advanced Javascript are your basic training. It clearly lays out the design decisions that went into the design of the Javascript language. Crawford exposes the many flaws of Javascript that emerged during the tit-for-tat browser wars of the last decade, but what emerged was an incredibly flexible language that can mimic the idioms of wide variety of other languages.

Related Posts:

Comments are closed.