JavaScript – A Different Beast, Part-7: Inheritance without Classes

Previous topic in this series: Objects without Classes

This is the seventh part of my tutorial on JavaScript. Focus of this series is to introduce developers who are comfortable with other programming languages like Java or C to the idiosyncrasies of JavaScript. Basic JavaScript knowledge is assumed, but is not necessary as the code samples are simple and self-explanatory. If you are new to JavaScript, I would suggest going through the topics below in the order given.

Topics:

  1. A different beast
  2. Types and Type Conversion
  3. Functions
  4. Scopes and Scope Chain
  5. Closures
  6. Objects without Classes
  7. Inheritance without Classes (You are here)
  8. Arrays, Maps and the for..in loop
  9. Literals and JSON
  10. Meta-Programming, Exceptions and Module Pattern

JavaScript employs Prototypical Inheritance (also called Differential Inheritance) as opposed to classical inheritance used in classical object oriented languages like Java or C++. It operates on the principle that most objects are derived from other, more general objects, and only differ in a few small aspects – the general object is called a prototype for the specific objects. As an example, ‘car’ is a good prototype for ‘fiat’ and ‘ferrari’, a ‘FourWheeler’ is a good prototype for ‘car’, a ‘Vehicle’ is a good prototype for ‘FourWheeler’. Every object points to a prototype for its default values and methods and then specifies how it is different from its prototype by declaring additional or overriding values or methods.

Prototype

All objects in JavaScript have a special internal property called [[prototype]] that points to its prototype object. This can be accessed using the Object.getPrototypeOf(anObject) method or by using the __proto__ property (not recommended). [Note that these two techniques will not work in IE]. All newly created objects are assigned a default object prototype by the runtime system, unless a prototype is defined by the developer. See code-sample below.

//creating an object
var ferrari = {
	name : 'ferrari',
};

//printing its prototype
var proto = Object.getPrototypeOf(ferrari);
console.log(proto, typeof(proto)); //Object{ } object (this is the default prototype)
console.log(ferrari.__proto__==proto); //true

var fiat = {
	name: 'fiat'
}

console.log(ferrari.__proto__ === fiat.__proto__); //true; all objects have the same default prototype

Property Lookup and Inheritance

When we attempt to access any property of an object (by typing employee.name or duck.quack() etc.) , if the property is not defined in that object then the JavaScript interpreter attempts to look it up on its prototype object. If it is not found even there, then it checks the prototype’s prototype (yes, prototypes are also objects; so they too can have prototypes) and so on till it reaches the end of the chain. See code sample below to see it in action. The __proto__ property can be used for setting the prototype as well, but it is not a recommended approach, nor is it supported in all browsers.

//code-sample
//creating two leaf-level objects
var ferrari = {
	name : 'ferrari'
};

var fiat = {
	name: 'fiat'
}

//prototype for ferrari and fiat
var car = {
	type: 'car',
	wheels : 4
}

//setting the prototype
ferrari.__proto__ = fiat.__proto__ = car;

//prototype for car
var vehicle = {
	start: function() { console.log('vrooom'); },
	stop : function() { console.log('stopped'); }
}

//setting car's prototype
car.__proto__ = vehicle;

//prototypes in action!
console.log(ferrari); //Object { name="ferrari", type="car", wheels=4}
console.log(fiat); //Object { name="fiat", type="car", wheels=4}
ferrari.start(); //vrooom
fiat.stop(); //stopped

Take a step back and look at the above code and you can see that fiat and ferrari has inherited member variables and methods from car and vehicle.

Note: When attempting to set a value into an object, the value always goes as a property of the object and never goes into the prototype. This is a very important point to note as we will see in the next page.

About these ads

About Rahul Mohan

Technical researcher interested in model-driven development of enterprise business applications. Passionate about web technologies and a huge admirer of open-source especially in the Java landscape. When I am not doing any of the above you can find me with my camera (www.flickr.com/photos/rahulmohan/) or listening to music. (In fact, the title of the blog is inspired by Led Zeppelin's Physical Graffiti. )

Posted on June 13, 2011, in JavaScript, Tutorial and tagged , , , , , , . Bookmark the permalink. Leave a comment.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

%d bloggers like this: