<\/span><\/h2>\n\n\n\nIn this challenge, we practice implementing inheritance<\/em> and use JavaScript prototypes<\/em> to add a new method to an existing prototype.<\/p>\n\n\n\n<\/span>Task<\/strong><\/span><\/h2>\n\n\n\nWe provide the implementation for a Rectangle<\/em> class in the editor. Perform the following tasks:<\/p>\n\n\n\n- Add an area<\/em> method to Rectangle<\/em>‘s prototype.<\/li>
- Create a Square<\/em> class that satisfies the following:
- It is a subclass of Rectangle<\/em>.<\/li>
- It contains a constructor and no other methods.<\/li>
- It can use the Rectangle<\/em> class’ area<\/em> method to print the area of a Square<\/em> object.<\/li><\/ul><\/li><\/ol>\n\n\n\n
Locked code in the editor tests the class and method implementations and prints the area<\/em> values to STDOUT.<\/p>\n\n\n\n<\/span>Solution – Day 5: Inheritance<\/strong><\/span><\/h2>\n\n\n\nclass Rectangle {\n constructor(w, h) {\n this.w = w;\n this.h = h;\n }\n}\n\n\/*\n * Write code that adds an 'area' method to the Rectangle class' prototype\n *\/\n Rectangle.prototype.area = function() {\n return (this.w * this.h);\n }\n class Square extends Rectangle {\n constructor(w){\n super(w, w);\n }\n }\n\/*\n * Create a Square class that inherits from Rectangle and implement its class constructor\n *\/\n\n\nif (JSON.stringify(Object.getOwnPropertyNames(Square.prototype)) === JSON.stringify([ 'constructor' ])) {\n const rec = new Rectangle(3, 4);\n const sqr = new Square(3);\n \n console.log(rec.area());\n console.log(sqr.area());\n} else {\n console.log(-1);\n console.log(-1);\n}<\/pre>\n\n\n\n