...

/

Prototypal Inheritance in ES5

Prototypal Inheritance in ES5

introduction to prototypal inheritance using an example (rectangle "is a" shape)

We'll cover the following...

Let’s start with an example, where we implement a classical inheritance scenario in JavaScript.

Press + to interact
function Shape( color ) {
this.color = color;
}
Shape.prototype.getColor = function() {
return this.color;
}
function Rectangle( color, width, height ) {
Shape.call( this, color );
this.width = width;
this.height = height;
};
Rectangle.prototype = Object.create( Shape.prototype );
Rectangle.prototype.constructor = Rectangle;
Rectangle.prototype.getArea = function() {
return this.width * this.height;
};
let rectangle = new Rectangle( 'red', 5, 8 );
console.log( rectangle.getArea() );
console.log( rectangle.getColor() );
console.log( rectangle.toString() );

Rectangle is a constructor function. Even though there were no classes in ES5, many people called constructor functions and their prototype ...