General Interface is an open source project hosted by the Dojo Foundation

Classes and Inheritance in JavaScript 1.x

JavaScript 1.x supports prototype inheritance. A class is defined by any function:

function Plant(latinName, englishName) {
  this.latinName = latinName;
  this.englishName = englishName;
}

The prototype field of the class function represents the prototypical instance of the class. A new instance of the class will be a copy of the prototype, including any fields and methods placed in the prototype.

Plant.prototype.relatedSpecies = new Array();

Plant.prototype.getLatinName = function() {
  return this.latinName;
};

Inheritance is supported by setting the prototype of a class function to a new instance of the superclass:

function Tree(latinName, englishName, flowering) {
  this.latinName = latinName;
  this.englishName = englishName;
  this.flowering = flowering;
};
Tree.prototype = new Plant();

Tree.prototype.isFlowering = function() {
  return this.flowering;
};

JavaScript supports an inheritance-aware instanceof operator. The following statements are true:

(var aPlant = new Plant()) instanceof Plant;
(var aTree = new Tree()) instanceof Plant;
(var aTree = new Tree()) instanceof Tree;

Because all classes implicitly extend the Object class, the following statement is also true: (var aPlant = new Plant()) instanceof Object;

Contents

Searching General Interface Docs

Enter labels to add to this page:
Please wait 
Looking for a label? Just start typing.