Pete Hodgson

Javascript without the this

Using closures in a different way

One of JavaScript’s many wrinkles is the way that this works. It can be quite confusing, since the semantics are quite different from the purely lexical scoping rules which apply for regular variables in JavaScript. What this references can often be totally unrelated to the lexical scope of a function. To work around that we often see tricks like:

Anyone who’s done much JavaScript development has felt this pain. Imagine if that was never needed. How could we get there? Well, one way would be to just never use this. Sounds crazy? Let’s see.

Read more…

Comments: 25
Keeping jQuery in Check

Keeping jQuery in Check

Segregated DOM makes for a maintainable JavaScript codebase

jQuery makes it really easy to work with the DOM and other browser APIs. Almost too easy. Having the almighty $ available to you at all times can lead to an architectural style that I refer to as “jQuery soup.”

JQuery soup muddies application code

A jQuery soup codebase is one where adhoc references to $ appear everywhere. AJAX calls and DOM manipulations are intermingled alongside application logic and business rules.

Taking this approach in a JavaScript app of any real significance will cause a lot of pain. Any part of your app that is reaching out to the DOM via $ is essentially mutating a big bag of shared global state. That means that whenever you want to modify or extend that part of the app you need to carefully maintain a large mental model of every DOM interaction in your head. That’s really hard to do, and very much prone to error.

Read more…

Comment: 1