Command Palette

Search for a command to run...

Hectal
Phase 7: this, Prototypes and Classes
JavaScript · Exercise 2 of 5 PreviousNext
Intermediate

A Rectangle constructor with shared methods

Write a constructor function (not a class) Rectangle(width, height) that stores width and height on the new object.

Add two methods on Rectangle.prototype, so all rectangles share them: area() returns width × height, and perimeter() returns 2 × (width + height).

Then create a 3 × 4 rectangle and show Area: 12, perimeter: 14 in the #out paragraph.

What Check tests

  1. new Rectangle(3, 4).area() returns 12
  2. new Rectangle(2, 5).perimeter() returns 14
  3. The methods live on the prototype, not on each rectangle
  4. Rectangle is a constructor function, not a class
  5. The page shows Area: 12, perimeter: 14

Stuck? One hint at a time

The solution unlocks after your first Check. Try first: that is where the learning happens.

Runs in your browser. Your code is saved here.

Your page

Press Run to see the page.

Console

Nothing logged yet.