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

Yehuda Shiran, Ph.D.
Doc JavaScript

Developer News
Microsoft Shows Off Silverlight 4, IE9 Plans
Metasploit Expands Vulnerability Test Framework
HyperCard Reborn?

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());
}


People who read this tip also read these tips:

Look for similar tips by subject:

internet.commediabistro.comJusttechjobs.comGraphics.com

Search:

WebMediaBrands Corporate Info

Legal Notices, Licensing, Permissions, Privacy Policy.
Advertise | Newsletters | Shopping | E-mail Offers | Freelance Jobs

webref The latest from WebReference.com Browse >
Rolling Out Your Own HTML Application Version Control · HTML 5: Client-side Storage · Working with Ajax Server Extensions
Sitemap · Experts · Tools · Services · Email a Colleague · Contact FREE Newsletters 
 The latest from internet.com
Wi-Fi Product Watch, November 2009 · Chip Market Recovering From '08 Collapse · Low-Cost Tools to Kickstart Your New Business