Overriding Methods & Properties
This lesson teaches how to override methods and properties in both ES5 and ES6 versions of JavaScript.
Overriding in 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
Javascript (babel-node)
//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 the prototype ofShape
constructor ...
Create a free account to access the full course.
By signing up, you agree to Educative's Terms of Service and Privacy Policy