Copying an Instance Without Losing Its Class

Riverside Pool’s desk tablet needs to preview Priya’s check-in before she taps in. The preview must leave her card unchanged. In Python, after = copy.deepcopy(priya) copies the card and its attributes while preserving its class, so after.check_in() leaves the original card’s three swims alone.

Try the Deep Copy

JavaScript’s structuredClone() makes a deep copy of supported data, including nested objects. Public fields holding functions can’t be cloned: they cause a DataCloneError. Does that make it a replacement for Python’s copy.deepcopy() here?

Keep these trimmed classes in pool-passes.js. They retain the check-in and printing behavior, with a new .copy() method to examine after trying the deep copy. Focus on the public swimmer and swims fields, the private #swimsLeft balance, and the shared checkIn() and describe() methods. These examples assume callers supply an integer balance from 0 through 10:

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";
  }

  checkIn() {
    this.swims += 1;
    return `${this.swimmer.name} checked in (${this.describe()})`;
  }

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

Append TenSwimCard below these classes in the same file. Its private balance and check-in method stay on the card; .copy() creates the preview:

Language: JavaScript
class TenSwimCard extends Pass {
  #swimsLeft;

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

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

  checkIn() {
    if (this.#swimsLeft === 0) {
      throw new RangeError(
        `No swims left on ${this.swimmer.name}'s card`
      );
    }
    this.#swimsLeft -= 1;
    return super.checkIn();
  }

  copy() {
    const card = new TenSwimCard(this.swimmer, this.#swimsLeft);
    card.swims = this.swims;
    return card;
  }
}

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.