Object-Oriented Programming with JavaScript, Part I: Inheritance: Inheritance through Prototyping - Doc JavaScript | WebReference

Object-Oriented Programming with JavaScript, Part I: Inheritance: Inheritance through Prototyping - Doc JavaScript


Object-Oriented Programming with JavaScript, Part I: Inheritance

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


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