Search⌘ K
AI Features

Overriding Methods & Properties

Explore how to override inherited methods and properties in JavaScript through practical examples using ES5 prototype functions and ES6 class syntax. Understand modifying inherited behavior with super calls to create flexible and customized object-oriented code.

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 ...

Javascript (babel-node)
//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 ...

Ask