...

/

Overriding Methods & Properties

Overriding Methods & Properties

This lesson teaches us how to override methods and properties in both the ES5 and ES6 versions of JavaScript.

Overriding in the ES5 Version

The properties and methods defined on the prototype of a constructor function can be overridden when inherited by another constructor function.

Example

Let’s take a look at an example implementing this:

Press + to interact
//constructor function Shape
function Shape(shapeName,shapeSides){
this.name = shapeName
this.sides = shapeSides
}
Shape.prototype.displayInfo = function(){
console.log(`Shape is ${this.name}`)
}
Shape.prototype.equalSides = 'no'
//constructor function Rectangle
function Rectangle(shapeName,shapeSides,shapeLength,shapeWidth){
Shape.call(this,shapeName,shapeSides)
this.length = shapeLength
this.width = shapeWidth
}
Rectangle.prototype = Object.create(Shape.prototype)
Rectangle.prototype.constructor = Rectangle
//overriding the value of "equalsides" property
Rectangle.prototype.equalSides = 'yes'
console.log(Rectangle.prototype.equalSides)
//overriding the displayInfo method
Rectangle.prototype.displayInfo = function(){
return this.sides
}
var rec = new Rectangle('Rectangle',4,3,5)
//shows sides instead of name
console.log(rec.displayInfo())

In the example above:

  • In line 6, the displayInfo function is defined on ...