Printing Instances With toString()

Riverside Pool’s front desk needs a morning list of passes, including each swimmer’s name, group, and entry type. Your subclasses already supply their descriptions. Now you’ll turn those objects into the lines staff need to read.

Give Passes a Printable Line

Python’s Pass.__str__() combines the swimmer’s fields with self.describe() in an f-string. Port that method as toString(). The JavaScript template literal builds the same line, and the subclass’s describe() supplies its own description, as in Python.

Keep these trimmed classes in pool-passes.js, then append the printing examples to that same file:

Language: JavaScript Filename: pool-passes.js
class Swimmer {
  constructor(name, group = "adult") {
    this.name = name;
    this.group = group;
  }
}

class Pass {
  swims = 0;

  constructor(swimmer) {
    this.swimmer = swimmer;
  }

  describe() {
    return "casual swim";
  }

  toString() {
    const { name, group } = this.swimmer;
    return `${name} (${group}): ${this.describe()}`;
  }
}

class TenSwimCard extends Pass {
  #swimsLeft;

  constructor(swimmer, swimsLeft = 10) {
    super(swimmer);
    this.#swimsLeft = swimsLeft;
  }

  describe() {
    return `ten-swim card, ${this.#swimsLeft} left`;
  }
}

Locked learning resources

Join us and get access to thousands of tutorials and a community of expert JavaScript developers.

Unlock This Lesson

Already a member? Sign-In

Locked learning resources

The full lesson is for members only. Join us and get access to thousands of tutorials and a community of expert JavaScript developers.

Unlock This Lesson

Already a member? Sign-In

Become a Member to join the conversation.