Javascript Object Inheritance before ECMAScript 6

Introduction

Here is the code to do inheritance before ECMAScript 6

Proper inheritance required multiple steps.

For instance, consider this example:

function Rectangle(length, width) {
    this.length = length;/*from  w  ww  .ja  va2 s. com*/
    this.width = width;
}

Rectangle.prototype.getArea = function() {
    return this.length * this.width;
};

function Square(length) {
    Rectangle.call(this, length, length);
}

Square.prototype = Object.create(Rectangle.prototype, {
    constructor: {
        value:Square,
        enumerable: false,
        writable: true,
        configurable: true
    }
});

var square = new Square(3);

console.log(square.getArea());              // 9
console.log(square instanceof Square);      // true
console.log(square instanceof Rectangle);   // true

Square inherits from Rectangle.

It must overwrite Square.prototype with a new object created from Rectangle.prototype as well as call the Rectangle.call() method.




PreviousNext

Related