Object Oriented JavaScript - Part 1
Aug 29 2011 11:04pm | | Share

Object Oriented JavaScript - Part 1

By Derek Santos

Read Part 2
Read Part 3

Back about 5-6 years ago in my PHP days, I was doing a lot of JavaScript.  It seems more and more that JavaScript will be a major player in the future with HTML5.  With that said, it's important to think about how HTML5 applications will be architected and organized.

There's a common misconception that JavaScript is not object oriented.  While OO principles may not be the foundation of JavaScript, it is possible to implement OO principles in JavaScript.

Prototypal vs. Class-based

JavaScript is a prototypal language.  What this means is that object behavior may be cloned based on other objects (or prototypes).  In traditional class-based languages, object relationships and behavior are typically defined at compile-time.  In a prototypal environment, they are defined at runtime.  This is why every object in JavaScript has a prototype property.

Defining a Class/Prototype with JavaScript

Here are two ways you can define a class with JavaScript.

Method 1: Within Constructor

This method is really simple and common.

function Person() {
    this.firstName = "Derek";
    this.lastName = "Santos";
}

var person = new Person();

Method 2: Using prototype

This method allows you to modify a class definition outside of its constructor.

 

function Person() { }
Person.prototype.firstName = "Derek";
Person.prototype.lastName = "Santos";

var person = new Person();

There is no super property in JavaScript (unless you create one yourself). Instead you need to use the "call" method.

AndroidPhone.prototype.startUp = function () {
    Device.prototype.startUp.call(this);
}

Declaring Class methods

To declare a method in a class, you can simply define it within the classes constructor like so.

function Person() {
    this.firstName = "Derek";
    this.lastName = "Santos";
    this.showName = function() {
        alert(this.firstName + " " + this.lastName);
    }
}

var person = new Person();
person.showName();

This is just the tip of the iceberg, many other OO concepts can be implemented in JavaScript.  Keep an eye out for Part 2 of this article where I'll talk about inheritance and other OO principles.