07 November 2008

OOP in JavaScript : Inheritance

There is no direct keyword (like 'extends' in Java) in JavaScript for inheritance. But its purpose can be served through 'prototype' attribute. Here, firstly an sample code is shown and then related points are described.

Sample Code of Inheritance:

function SuperClass(name)
this._name = name;

this.getName = function()

return this._name;


// inheritance occurs here

SubClass.prototype = new SuperClass;
function SubClass(name, address)

// calling constructor of super class


//new attributes

this._address = address;

this.getAddress = function()

return this._address;


Object Creation & Usage:
Please observe the following code.

var sub = new SubClass("Alor Chhota","Mohammadpur");

alert("Name: " + sub.getName());
alert("Address: " + sub.getAddress());

Extending Super Class in Sub Class:
The following command asks to extend SuperClass in SubClass.
SubClass.prototype = new SuperClass;

Passing Parameters to SuperClass Constructor:
If you see the above code, you'll find the following line -

This is actually the call of SuperClass constructor. Look closely at the sent parameters. The first parameter must be 'this' (SubClass) and the parameters of SuperClass will follow it. More descriptively, 2nd paramter of 'call' function is actually the 1st parameter of SuperClass, 3rd of call is 2nd of SuperClass etc.



© 2007 t!ps n tr!cks: OOP in JavaScript : Inheritance

Template unik dari rohman

---[[ Skip to top ]]---