open core »

Object Oriented Javascript

Recently, I've been playing with Object Oriented Javascript. This language, besides it's chaotic nature, can be very powerful when used with some best practices (humm, that's funny, I'd swear I've heard this before).

One of the most interesting things about Javascript OO is the way to define a Class. Actually there is no keyword "class" at all. So here's an example on how to create a class Book in Javascript:

/**this will be the constructor method,
that automatically creates the class**/

function Book (isbn, title, author) {
    this.isbn = isbn;
    this.title = title;
    this.author = author;
}

/** And now the getters **/

Book.prototype.getISBN = function () {
    return this.isbn;
}

Book.prototype.getTitle = function () {
    return this.title;
}

Book.prototype.getAuthor = function () {
    return this.author;
}

If your class has attributes that are not passed as constructor arguments, you can declare the attribute just like we did for the methods:

Book.prototype.numTimesRead = 5;

//a setter
Book.prototype.setNumTimeRead = function (n) {
    this.numTimesRead = n;
}

Now if we wish to instantiate our class, it's identical to most OO languages:

var mybook = new Book("123", "Dive into Python", "Mark Pilgrim");

//I tried to output this the ugliest way possible :P
document.getElementsByTagName("body").innerHTML = "Title: "+mybook.getTitle();

This will (pwn your body element) print the Book title, you can add any other info as you wish.

You may find more on object oriented programming with Javascript at the Mozilla's Developer site.