Day 5: Inheritance Solution
Hello Friends in this article i am gone to share Hackerrank 10 days of javascript solutions with you. | Day 5: Inheritance Solution.
Also visit this link:ย Day 4: Classes Solution
Day 5: Inheritance Solution
Objective
In this challenge, we practice implementingย inheritanceย and use JavaScriptย prototypesย to add a new method to an existing prototype.
Task
We provide the implementation for aย Rectangleย class in the editor. Perform the following tasks:
- Add anย areaย method toย Rectangleโs prototype.
- Create aย Squareย class that satisfies the following:
- It is a subclass ofย Rectangle.
- It contains a constructor and no other methods.
- It can use theย Rectangleย classโย areaย method to print the area of aย Squareย object.
Locked code in the editor tests the class and method implementations and prints theย areaย values to STDOUT.
Solution โ Day 5: Inheritance
classย Rectangleย { ย ย ย ย constructor(w,ย h)ย { ย ย ย ย ย ย ย ย this.wย =ย w; ย ย ย ย ย ย ย ย this.hย =ย h; ย ย ย ย } } /* ย *ย ย Writeย codeย thatย addsย anย 'area'ย methodย toย theย Rectangleย class'ย prototype ย */ ย Rectangle.prototype.areaย =ย function()ย { ย ย ย ย ย returnย (this.wย *ย this.h); ย } ย classย Squareย extendsย Rectangleย { ย ย ย ย ย constructor(w){ ย ย ย ย ย ย ย ย ย super(w,ย w); ย ย ย ย ย } ย } /* ย *ย Createย aย Squareย classย thatย inheritsย fromย Rectangleย andย implementย itsย classย constructor ย */ ifย (JSON.stringify(Object.getOwnPropertyNames(Square.prototype))ย ===ย JSON.stringify([ย 'constructor'ย ]))ย { ย ย ย ย constย recย =ย newย Rectangle(3,ย 4); ย ย ย ย constย sqrย =ย newย Square(3); ย ย ย ย ย ย ย ย console.log(rec.area()); ย ย ย ย console.log(sqr.area()); }ย elseย { ย ย ย ย console.log(-1); ย ย ย ย console.log(-1); }