Skip to curriculum
Jump to the editor

9.3. Methods only real instances can call

Medium
Topics

This question is in

9. Prototypes and classes
20–30 min

A payment form adds prices together, and a bug elsewhere passes in a plain object { amount: 1050, currency: "USD" }, or an object made with Object.create(Money.prototype). Both pass an instanceof Money check, and both would be added as if they were real. A brand check makes a class's methods refuse any object that its constructor did not build: they throw a TypeError instead of computing with data nobody validated.

Write the class Money in money.js. It holds a whole number of cents and a currency code, and every method, getter and the static Money.isMoney accept only objects that new Money (or a subclass's super) built.

Signature

JAVASCRIPT
class Money {
  constructor(amount, currency)
  get amount()          // the cents
  get currency()        // the code, like "USD"
  format()              // "10.50 USD"
  add(other)            // a new Money
  static isMoney(value) // true or false
}
  • amount: a whole number of cents; negative amounts are allowed.
  • currency: exactly three capital letters A to Z.

Requirements

  1. amount and currency return what the constructor received.
  2. format() returns the amount in whole units with two decimals, a space and the currency: 1050 gives "10.50 USD", -5 gives "-0.05 USD".
  3. A Money object has no own properties, and assigning amount or currency from outside does not change them.
  4. format, add and the getters throw a TypeError when this is not an object that new Money built: a plain look-alike object, an object made with Object.create(Money.prototype), a Proxy around a real Money, or undefined (a method taken off its object).
  5. A real Money stays real when its prototype is changed: Money.prototype.format.call(money) still works after Object.setPrototypeOf(money, null).
  6. Objects built by a subclass (class Price extends Money) are real Money objects.
  7. Money.isMoney(value) returns true only for real Money objects and false for everything else, including primitives, null, undefined, Money itself and Money.prototype. It never throws.
  8. add(other) returns a new real Money with the sum and the same currency, and changes neither input.
  9. add throws a TypeError when other is not a real Money, and a RangeError when the currencies differ.
  10. The constructor throws a TypeError when amount is not an integer (1.5, "100", NaN, Infinity) or currency is not three capital letters ("usd", "US", 840, missing). Calling Money without new throws a TypeError.

Examples

JAVASCRIPT
const price = new Money(1050, "USD");
price.format();                         // "10.50 USD"
price.add(new Money(-50, "USD")).amount; // 1000
Money.isMoney(price);                   // true
JAVASCRIPT
const impostor = Object.create(Money.prototype);
impostor instanceof Money;              // true, but:
impostor.format();                      // TypeError
Money.isMoney(impostor);                // false
Money.isMoney({ amount: 1, currency: "USD" }); // false
JAVASCRIPT
const price = new Money(250, "USD");
Object.setPrototypeOf(price, null);
Money.prototype.format.call(price);     // "2.50 USD"
price.add(new Money(1, "EUR"));         // TypeError: price has no add now
new Money(250, "USD").add(new Money(1, "EUR")); // RangeError

Environment

  • Plain JavaScript in a browser page; the tests use the global class Money from money.js.
  • instanceof and prototype checks are not enough: requirement 4 includes an object whose prototype is Money.prototype.

Hints

  1. What does reading a private field do when the object does not have that field?
  2. Which operator asks "does this object have this private field?" without throwing, and what does it need its right side to be?

The explanation comes with the course

A walkthrough of every line of a solution, the mistakes the tests catch, other ways to write it, and links to the lessons that teach each idea.

  • Every line explained
  • The mistakes each test catches
  • Links to the lessons behind it
Back to the question
Loading the editor…