How to do inheritance in JavaScript ES5?
Answers
JavaScript's prototype-based inheritance is interesting and has its uses, but sometimes one just wants to express classical inheritance, familiar from C++ and Java. This need has been recognized by the ECMAScript committee and classes are being discussed for inclusion in the next version of the standard. It was surprisingly hard for me to find a good and simple code sample that shows how to cleanly and correctly express inheritance with ES5 (a lot of links discuss how to implement the pre-ES5 tools required for that) and explains why the thing works. Mozilla's Object.Create reference came close, but not quite there because it still left some open questions. Hence this short post. Without further ado, the following code defines a parent class named Shape with a constructor and a method, and a derived class named Circle that has its own method: // Shape - superclass // x,y: location of shape's bounding rectangle function Shape(x, y) { this.x = x; this.y = y; } // Superclass method Shape.prototype.move = function(x, y) { this.x += x; this.y += y; } // Circle - subclass function Circle(x, y, r) { // Call constructor of superclass to initialize superclass-derived members. Shape.call(this, x, y); // Initialize subclass's own members this.r = r; } // Circle derives from Shape Circle.prototype = Object.create(Shape.prototype); Circle.prototype.constructor = Circle; // Subclass methods. Add them after Circle.prototype is created with // Object.create Circle.prototype.area = function() { return this.r * 2 * Math.PI; }