Easy Object Oriented JavaScript

I love object oriented programming. Not because I have the crazy misconception that it is the ultimate programming paradigm but because it fulfills my desire to organize, categorize and modularize my code. Consequently I like to bring OO ideas into whatever language I’m working on. Now being primarily a ColdFusion developer I work a lot with JavaScript. But one thing that really took me a while to get a grasp of is making my JavaScript code object oriented.

I happen to really like JavaScript…mostly. It has some really weird quirks sometimes and parts of it seem poorly designed but overall it is a very powerful and fun language to work with. Its power and quirkiness is very evident when trying to write object oriented code. There seem to be at least three ways to write OO code with JS with all three being completely different. JavaScript just isn’t clear when it comes to OO and doesn’t have any easy to use mechanisms for doing things like inheritance. This is what really tripped me up for a long time. I’d read tutorials and books that would cover the subject (OO) but they’d all do things differently and not explain why they were doing it the way they were.

Thankfully though I stumbled upon Douglas Crockford’s JavaScript videos this year and opened my eyes on a few things when writing object oriented code. This is what I’ve learned and how I do OO with JavaScript now.

First thing first, objects. In JS, creating an object is as easy as doing the following:

myObject = {};

Wow, that was easy. No “new” operator or any other mumbo jumbo (is new considered an operator?). Just that one simple line. That simple line creates a singleton object as soon as it is executed. Usually though, you want to have some actually have some functionality in your objects so let’s do that now. There are a couple of ways to do that.

// OPTION 1
myObject1 = {
    sayHello: function(){
        alert("hello world");
    },
    sayGoodbye: function(){
        alert("goodbye");
    }
}

myObject.sayHello(); // alerts hello
myObject.sayGoodbye(); // alerts goodbye

// OPTION 2
myObject2 = {};

myObject2.sayHello = function(){
    alert("hello world");
}

myObject2.sayGoodbye = function(){
    alert("goodbye");
}

myObject2.sayHello(); // alerts hello
myObject2.sayGoodbye(); // alerts goodbye

Both option 1 and option 2 do the same thing but have somewhat different syntaxes. I don’t know if I use either more than the other. It just depends of the circumstances.

Now one thing you might be wondering is how to have multiple instances of this object? JavaScript doesn’t really have a concept of classes, only objects, which is what this is. Essentially, you’d need to make a new copy of the object every time you wanted a new instance. This is actually very, very easy to do. Simply wrap the object in a function that returns a new instance. Here is how it works.

function myObject(){
    var obj = {};

    obj.sayHello = function(){
        alert("hello world");
    }

    obj.sayGoodbye = function(){
        alert("goodbye");
    }

    return obj;
}

myObject = myObject();
myObject.sayhello();
myObject.sayGoodbye();

The wrapper function acts as a class and constructor for the object. Every time the myObject function is called it returns a new instance of your object. You can even have private methods and can pass in constructor parameters.

function greeter(name){
    var obj = {};
    obj.name = name;

    // private function
    function greet(){
        alert("hello " + obj.name);
    }

    obj.sayHello = function(){
        greet();
    }

    return obj;
}

myObject = greeter("Dustin");
myObject.sayhello(); // alerts "hello Dustin"

Simple and concise. Another nice thing about this method is that inheritance is a breeze.

function parentObject(){
    var obj = {};

    obj.sayGoodbye = function(){
        alert("goodbye");
    }

    return obj;
}

function greeter(name){
    // This causes the object to "inherit" from parentObject
    var obj = parentObject();

    obj.name = name;

    // private function
    function greet(){
        alert("hello " + obj.name);
    }

    obj.sayHello = function(){
        greet();
    }

    return obj;
}

myObject = greeter("Dustin");
myObject.sayhello(); // alerts "hello Dustin"
myObject.sayGoodbye(); // alerts "goodbye" - sayGoodbye is inherited from parentObject

What is happening is that greeter calls the parentObject “constructor” to get an object, then modifies it with its own methods, essentially inheriting the functionality from parentObject. Very powerful but very simple. This is only possible because JavaScript objects are modifiable. Many language do not allow objects to be modified with new methods but JavaScript is an exception. Scala, Ruby, and other languages allow this and, in my opinion, this makes for some very concise yet powerful features.

Unfortunately, this method of doing OO in JS is not something I’ve seen even though it is very straight forward. I suspect that is because object mutability seem to be a rare thing among most mainstream languages like Java. As languages like Ruby gain in popularity I imagine that might change.