call(back)

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

  • Polygon and Square are constructor functions. The grader reads their source, so class syntax fails.
  • Fields live on instances, and methods live on prototypes, shared by every instance.
  • Square.prototype inherits from Polygon.prototype, instanceof works for both, and each prototype's constructor points back to its function.
  • Square.prototype carries no height or width of 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.

Asked at