February 18, 2001 - Establishing an Object Hierarchy | WebReference

February 18, 2001 - Establishing an Object Hierarchy

Yehuda Shiran February 18, 2001
Establishing an Object Hierarchy
Tips: February 2001

Yehuda Shiran, Ph.D.
Doc JavaScript

There are two different ways to establish an hierarchy of classes in JavaScript. The first method to create an object as a subclass of another object, is to call the superclass constructor function inside the subclass object definition. Let's look at the following example:

function superClass() {
  this.bye = superBye;
  this.hello = superHello;
}
function subClass() {
  this.inheritFrom = superClass;
  this.inheritFrom();
  this.bye = subBye;
}
function superHello() {
  return "Hello from superClass";
}
  
function superBye() {
  return "Bye from superClass";
}
function subBye() {
  return "Bye from subClass";
}

Click here to invoke the following script that activates these objects:

var newClass = new subClass();
function printSub() {
  alert(newClass.bye());
  alert(newClass.hello());
}

Convince yourself that it is working correctly. The methods bye() and hello() are first defined in superClass(). The method bye() is being overridden in subClass(). The first two lines of subClass() does the original inheritance between the two classes. You first define the inheritFrom method, and then you call it:

this.inheritFrom = superClass;
this.inheritFrom();

The second method to establish a class hierarchy is by creating an object of the superclass and assign it as a prototype of the subclass object:

subClass.prototype = new superClass;

And the whole example is:

function superClass1() {
  this.bye = superBye1;
  this.hello = superHello1;
}
function subClass1() {
  this.bye = subBye1;
}
subClass1.prototype = new superClass1;
function superHello1() {
  return "Hello from superClass";
}
  
function superBye1() {
  return "Bye from superClass";
}
function subBye1() {
  return "Bye from subClass";
}

Click here to invoke the following script that activates these objects:

var newClass1 = new subClass1();
function printSub1() {
  alert(newClass1.bye());
  alert(newClass1.hello());
}

Convince yourself that you get the same results as before: bye() from subClass() and hello() from superClass().