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
SuperClass.call(this,name);
//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 -
SuperClass.call(this,name);
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.
07 November 2008
OOP in JavaScript : Inheritance
Posted by আলোর ছটা at 6:03 PM
Labels: JavaScript, OOP
Subscribe to:
Post Comments (Atom)
0 Comments:
Post a Comment