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
|
