Overriding Methods & Properties
This lesson teaches us how to override methods and properties in both the ES5 and ES6 versions of JavaScript.
We'll cover the following...
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 Shapefunction Shape(shapeName,shapeSides){this.name = shapeNamethis.sides = shapeSides}Shape.prototype.displayInfo = function(){console.log(`Shape is ${this.name}`)}Shape.prototype.equalSides = 'no'//constructor function Rectanglefunction Rectangle(shapeName,shapeSides,shapeLength,shapeWidth){Shape.call(this,shapeName,shapeSides)this.length = shapeLengththis.width = shapeWidth}Rectangle.prototype = Object.create(Shape.prototype)Rectangle.prototype.constructor = Rectangle//overriding the value of "equalsides" propertyRectangle.prototype.equalSides = 'yes'console.log(Rectangle.prototype.equalSides)//overriding the displayInfo methodRectangle.prototype.displayInfo = function(){return this.sides}var rec = new Rectangle('Rectangle',4,3,5)//shows sides instead of nameconsole.log(rec.displayInfo())
In the example above:
-
In line 6, the
displayInfo
function is defined on ...