February 22, 2001 - Adding Methods and Properties on the Fly | WebReference

February 22, 2001 - Adding Methods and Properties on the Fly

Yehuda Shiran February 22, 2001
Adding Methods and Properties on the Fly
Tips: February 2001

Yehuda Shiran, Ph.D.
Doc JavaScript

There are two ways to establish an inheritance relationship between a superclass and a subclass. The first one is to run the superclass constructor function in the subclass constructor, subClass(). Here is an example:

function superClass() {
  this.bye = superBye;
  this.hello = superHello;
}
function subClass() {
  this.inheritFrom = superClass;
  this.inheritFrom();
  this.bye = subBye;
  
  
}

The other way to inherit from a superclass is by protyping. Here is an example:

function superClass1() {
  this.bye = superBye1;
  this.hello = superHello1;
}
function subClass1() {
  this.bye = subBye1;
}
subClass1.prototype = new superClass1;

It seems as if we have two 100%-equivalent ways to inherit methods and properties, but this is not accurate. Prototyping is better because it supports dynamic inheritance. You can define superclass methods and properties, after the constructor is done, and have the subclass object pick the new methods and properties. Here is an example that defines the blessyou() functions:

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";
}
var newClass1 = new subClass1();
superClass1.prototype.blessyou = superBlessyou;
function superBlessyou() {
  return "Bless You from superClass";
}
function printSub1() {
  alert(newClass1.bye());
  alert(newClass1.hello());
  alert(newClass1.blessyou());
}

Notice the three lines:

superClass1.prototype.blessyou = superBlessyou;
function superBlessyou() {
  return "Bless You from superClass";
}

We define the function blessyou() and then print it from the subclass object:

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