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
Google Going Native With Chrome
Mozilla Fixes Firefox Flaws as 3.5 Release Nears
Microsoft and Novell Still Bosom Buddies

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 >
XML and PHP Simplified · Creating a ASP.NET Contact Form · Data Filtering with PHP
Sitemap · Experts · Tools · Services · Email a Colleague · Contact FREE Newsletters 
 The latest from internet.com
Intel to Host Live Nehalem Q&A · 12 Tips to Troubleshoot Network File-Sharing · 10 Tips for Selling on Kijiji


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