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

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

Object-Oriented Programming with JavaScript, Part I: Inheritance

Inheritance through Functions

Although JavaScript does not support an explicit inheritance operator, you can implement inheritance in other ways. There are two different ways to establish a hierarchy of classes in JavaScript. The first method to create an object as a subclass of another object, is to call the superclass constructor function inside the subclass object definition. Let's look at the following example:

function superClass() {
  this.bye = superBye;
  this.hello = superHello;
function subClass() {
  this.inheritFrom = superClass;
  this.bye = subBye;
function superHello() {
  return "Hello from superClass";
function superBye() {
  return "Bye from superClass";
function subBye() {
  return "Bye from subClass";

Click here to invoke the following assignment and function that activate these objects:

function printSub() {
  var newClass = new subClass();

Convince yourself that it is working correctly. The methods bye() and hello() are first defined in superClass(). The method bye() is being overridden in subClass(). The first two lines of subClass() does the original inheritance between the two classes. You first define the inheritFrom method, and then you call it:

this.inheritFrom = superClass;

Let's take another example. Here is the definition of superclass() and subclass() (different from the above superClass() and subClass()):

function superclass() {
  this.info = alert("Defining the Superclass");
function subclass() {
  this.inheritFrom = superclass;
  this.info = alert("Overriding the Superclass");

To activate the generation of subclass(), click here. This button calls the following function:

function createSubclass() {
  var newClass = new subclass();

Notice the alert boxes. They show that the info method is first defined in superclass() and then is being overridden in subclass().

Next: How to implement inheritance with prototyping


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/3.html