Objectifying Javascript
I’ve been out of town for two weeks, so I’m just now catching up on all my javascript reading. Here’s the first of what will no doubt be a flurry of posts today.
I found this linked to via ajaxian. It’s a great article on object oriented practices using javascript. A lot of what Jonathan Snook goes over in his article on Objectifying Prototype is taken care of for you using Prototype.js’s Class.create methods and Object.extend methods. I highly recommend reading up on these functions (linked to at the bottom of the article). But this overview is really a great primer for writing class based javascript.
Jonathan goes over this himself, but I’ll sound off on writing code this way. If you’ve ever written java or php, object oriented code won’t be new to you. Until the Prototype.js library showed up, I never really wrote my javascript this way, mostly because I just didn’t write that much of it and it was limited to relatively small functionality.
Now when I write code it’s either for a larger application (like my history toolbar) or I design it to be resuable, even if it’s something that might never be reused (like my random cookie maker). Object oriented code is not only cleaner and easier to maintain because the relationship to the functions and the data are self contained, but also easier to extend in ways you may not have previously considered. If you’re still declaring variables and writing tons of functions, read this short primer and then dig into Prototype.js’s methods for creating and extending objects.
