Object Oriented JavaScript

javascript.gifJavascript has invaded my life. And I like it.

I have developed web applications for quite some time, writing Javascript off an often unnecessary tool that simply added frills. Over the course of this year – with the birth of the Ajax hype – I realize my error. I began inserting javascript all over hell’s half acre and raving about its sweetness. I’ve grown in a year.

As I develop more javascript-rich web applications for my amusement and my job, I am constantly seeking better ways to structure both data and code. It wasn’t until a month ago that I really began to dig into the Prototype and Script.aculo.us code (rather than simply using it) and began to grow aware of what was actually going on. Object Oriented Javascript.

I think it is important to note (so I don’t look like a complete nitwit) that I was aware that Javascript had this capability a couple of months back before I picked up and started using the afore mentioned Javascript libraries…I just had no drive to learn it and spot where it was being used. I have seen the light and it is good.

What are its benefits? Well, pretty much the same applies to Javascript that applies to any other programming language…OOP helps increase organization and reduce un-needed redundancy. And best of all? It helps prevent dual-declared functions and variables. That is the reason I chose to begin my quest for OO-JS familiarity.

I had gone hunting at a few other sites that claimed to be good references (obviously) of OO-JS, but they lacked the topic of inheritance, which is the real strength of any OOP Language. The most helpful article I found on the topic was at WebReference. They discuss the use of prototype (Not the Javascript Library). Here’s a quick excerpt, but I’d suggest you read the article for yourself!

Excerpt from WebReference

function Person() {
      this.name = "Rob Roberson";
      this.age = 31;
}

function Employee() {
      this.dept = "HR";
      this.manager = "John Johnson";
}

Employee.prototype = new Person();

var Ken = new Employee();

Ken is in the prototype chain of Employee, Person, and Object.

Check it out. Use it. You’ll like it. You’re applications will like it. Oh, and it may prove useful to check out some Javascript Coding Conventions.