Netscape DevEdge

Skip to: [content] [navigation]

inheritFrom - A Simple Method of Inheritance upon Demand

Introduction

In C++ and similar languages, classes are extended through inheriting from parent classes. This ability to extend an existing class is a very useful technique in object oriented programming. JavaScript uses prototype-based inheritance rather than class-based inheritance as found in C++. inheritFrom is a simple function which supports inheriting properties and methods from an object into an existing object without completely replacing the existing prototype.

Script

inheritFrom.js implements a function:

inheritFrom(Object aThis, Object aParent)

inheritFrom will copy the properties of the object aParent to the object aThis.

Example 1

This example illustrates adding the properties and methods of CExtraStuff to the prototype of CSimpleStuff at run-time. Note that CExtraStuff must be defined before the script which contains the definition of CSimpleStuff is loaded since an instance of CExtraStuff is created when the script loads.

function CExtraStuff(/* String */ aValue)
{
  this.mExtraValue = aValue;
}

CExtraStuff.prototype.extraMethod = function()
{
  alert('Extra value is ' + this.mExtraValue);
};

function CSimpleStuff(/* String */ aValue)
{
  this.mValue = aValue;
}

CSimpleStuff.prototype.simpleMethod = function()
{
  alert('Simple value is ' + this.mValue);
};

inheritFrom(CSimpleStuff.prototype, new CExtraStuff('default extra value'));

function doExample1()
{
  var simple = new CSimpleStuff('default simple value');
  simple.simpleMethod();
  simple.extraMethod();
}

Example 2

This example illustrates adding the properties and methods of CParent to each instance of the CChild at construction time. Note that CParent need not be defined before the script which contains CChild is loaded. However, CParent must be defined before the first instance of CChild is created.

function CParent(/* String */ aValue)
{
  this.mParentValue = aValue;
}

CParent.prototype.parentMethod = function()
{
  alert('Parent value is ' + this.mParentValue);
};

function CChild(/* String */ aValue)
{
  this.mValue = aValue;
  inheritFrom(this, new CParent('default parent value'));
}

CChild.prototype.childMethod = function()
{
  alert('Child value is ' + this.mValue);
};


function doExample2()
{
  var child = new CChild('default child value');
  child.childMethod();
  child.parentMethod();
}
A+R