Object Oriented JavaScript - Part 2
Sep 12 2011 11:01pm | | Share

Object Oriented JavaScript - Part 2

By Derek Santos

Read Part 1
Read Part 3

In a previous post, I covered the basics of Object Oriented JavaScript. In this post, we'll take a closer look at inheritance.  Remember that JavaScript is a prototypal language. Instead of the traditional "is a" relationship, JavaScript inheritance has a "is now a" or "has become a" relationship.  The reason for this is that JavaScript is an interpreted language, and does not get compiled.   In classical OOP, inheritance means a subclass "is and has always been a" type of its superclass.  In JavaScript, an object always starts off as an independent entity and can then be assigned a relationship to some other object.  Let's look at some examples.

Inheriting from another object

To make an object inherit from another object, you use the objects prototype property.

function Device() {}
Device.prototype.startUp = function () {
    alert('device start up');
}

function AndroidPhone() {}
AndroidPhone.prototype = new Device(); //AndroidPhone inherits from Device

var device = new AndroidPhone();
device.startUp();

Overriding methods

To override a method, simply define it in your new object.

AndroidPhone.prototype.startUp = function () {
    alert("AndroidPhone starting up...");
}

Calling methods on the superclass

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);
}

The call method accepts an argument specifying the this property. It is used to define the context in which you are calling the method. In this case "this" will refer to AndroidPhone.

Digging Deeper

There's a lot you can do with JavaScript inheritance. There are countless examples and libraries out there that try to make OOP in JavaScript easier and more streamlined. In my next post, I'll take a look at some of those libraries and see how OOP in JavaScript can be made easier.