Inheritance Without class
Explain how inheritance works in JavaScript, then write this pair using functions only:
class Polygon {
constructor(height, width) {
this.height = height;
this.width = width;
}
area() {
return this.height * this.width;
}
}
class Square extends Polygon {
constructor(side) {
super(side, side);
}
setSide(n) {
this.height = this.width = n;
}
}Rules
PolygonandSquareare constructor functions. The grader reads their source, soclasssyntax fails.- Fields live on instances, and methods live on prototypes, shared by every instance.
Square.prototypeinherits fromPolygon.prototype,instanceofworks for both, and each prototype'sconstructorpoints back to its function.Square.prototypecarries noheightorwidthof its own.
Hints
Hint 1
super(side, side) becomes Polygon.call(this, side, side): run the parent constructor against the new object.
Hint 2
Link the prototypes with Square.prototype = Object.create(Polygon.prototype), then put Square.prototype.constructor = Square back.
Hint 3
Add setSide to Square.prototype after replacing it, or the new prototype will not have it.