...

/

Class-based Inheritance in ES5

Class-based Inheritance in ES5

This lesson teaches us how class-based inheritance is implemented in the ES5 version by using constructor functions.

Inheritance Using Constructor

Objects are inherited from the constructor function’s prototype object using the prototype chain. The same concept could also be used in the implementation of class-based inheritance, i.e., where one class inherits the properties (including methods) from another class.

There is no class keyword in the ES5 version of JavaScript; hence we use constructor functions to implement a class. Now let’s learn how class-based inheritance can be implemented using constructor functions, i.e., how one constructor function can inherit from another.

Example

Below is an example that is implementing class-based inheritance using constructor functions:

Press + to interact
//constructor function Shape
function Shape(shapeName,shapeSides){
this.name = shapeName
this.sides = shapeSides
}
//defining the property "equalSides" on the prototype of Shape
Shape.prototype.equalSides = 'yes'
//displaying Shape.prototype
//it will show "equalSides" that is defined on the prototype
console.log(Shape.prototype)
//constructor function Rectangle
function Rectangle(shapeName,shapeSides,length,width){
//call function invoked to inherit and initialize the properites of Shape for Rectangle
Shape.call(this,shapeName,shapeSides)
//properties of rectangle
this.length = length
this.width = width
}
//Setting Shape object to be the prototype of Rectangle
//so Rectangle can inherit Shape prototype properties
//through the new object created
Rectangle.prototype = Object.create(Shape.prototype)
//setting Rectangle's prototype constructor so that it points to itself
Rectangle.prototype.constructor = Rectangle
//defining a method "area" on the prototype of Rectangle
Rectangle.prototype.getArea = function(){
return this.length*this.width
}
//displaying Rectangle.prototype
//it will show getArea that is defined on its prototype
//and constructor function pointing to Rectangle itself
console.log(Rectangle.prototype)
//creating a Rectangle object instance
var obj = new Rectangle('Rectangle',4,3,5)
//displaying properties
console.log("Name:",obj.name)
console.log("Sides:",obj.sides)
console.log("All sides are equal:",obj.equalSides)
console.log("Length:",obj.length)
console.log("Width",obj.width)
console.log("Area:",obj.getArea())

call Method

Before we get into the details of the code above, let’s discuss what a call function does.

The purpose of call is to invoke a method, defined anywhere, in the current context. Hence, this is passed as its first parameter. In the code above, call ...