spacer

Webref WebRef   Sitemap · Experts · Tools · Services · Newsletters · About i.com

home / experts / javascript / column79


Object-Oriented Programming with JavaScript, Part I: Inheritance

Developer News
News Flash: Adobe Has iPhone Workaround
Adobe's Flash 10.1 Goes Mobile (Minus iPhone)
A Salute to Visionary CEOs

Inheritance through Prototyping

The second and more robust method to establish a class hierarchy is by creating an object of the superclass and then assign it as a prototype of the subclass object. Suppose our superclass is superClass and our subclass is subClass. The prototype assignment would look like this:

subClass.prototype = new superClass;

Let's take the example from Page 3 and use the prototype assignment instead of these assignments inside the subClass() defintion:

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

Here is the new code:

function superClass() {

  this.bye = superBye;
  this.hello = superHello;
}

function subClass() {
  this.bye = subBye;
}
subClass.prototype = new superClass;

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 creates an instance of subClass():

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

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

Next: How to add properties after the object is created

http://www.internet.com

internet.commediabistro.comJusttechjobs.comGraphics.com

Search:

WebMediaBrands Corporate Info

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

webref The latest from WebReference.com Browse >
Building a Banking Application Home Page with OOP · Mixing Scripting Languages · Review: phpFox, a Social Networking CMS with all the Bells and Whistles
Sitemap · Experts · Tools · Services · Email a Colleague · Contact FREE Newsletters 
 The latest from internet.com
Enterprise 2.0: Social Networking in the Cloud · BroadSoft Marketplace Hastens Pace of Telephony Innovation · Review: HTC Hero for Sprint


Produced by Yehuda Shiran and Tomer Shiran
All Rights Reserved. Legal Notices.
Created: March 12, 2001
Revised: March 12, 2001

URL: http://www.webreference.com/js/column79/4.html