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
ActiveState Debuts Open Source Business Suite
Salesforce Offers Visual App Builder
Codesion Steps Out From CVS's Shadow

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


The Network for Technology Professionals

Search:

About Internet.com

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

webref The latest from WebReference.com Browse >
Use Web Caching to Make Your Web Site Faster · Creating an Online Shopping Cart Mechanism in PHP · Log JavaScript Errors Using an AJAX-driven Web Service
Sitemap · Experts · Tools · Services · Email a Colleague · Contact FREE Newsletters 
 The latest from internet.com
Configuring Granular Settings for a Database Level Audit · The Perils of a Web 2.0 Transition on Your Business Processes · Facebook Redesigns Site —Again — Nears 400M Mark


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