Protecting State With # Fields and get

Swimmer and Pass now run in JavaScript, so the next class to move is the ten-swim card. Priya Nair has three swims left on hers, already paid for, so that number should go down only when she swims.

The Python class protects the count with a leading underscore and a @property. Both habits carry over. What’s new is that JavaScript can make the count truly private, out of reach of any code outside the class.

Keep the Count in a # Field

Here’s the Python card, with the count behind an underscore and use_swim() taking one swim at a time:

Language: Python
class TenSwimCard:
    def __init__(self, swimmer, swims_left=10):
        self.swimmer = swimmer
        self._swims_left = swims_left

    def use_swim(self):
        if self._swims_left == 0:
            raise ValueError(
                f"No swims left on {self.swimmer.name}'s card"
            )
        self._swims_left -= 1

The underscore is a promise between programmers that Python doesn’t enforce, and JavaScript’s this._swimsLeft uses the same convention, mostly seen in older code. Python’s name-mangled self.__swims_left has no counterpart: this.__swimsLeft is an ordinary property anyone can read and change.

For real privacy, JavaScript has private fields. You declare one in the class body with a # in front of its name, then use it as this.#swimsLeft.

In useSwim(), throw does what Python’s raise does. JavaScript has no ValueError, so useSwim() throws a RangeError for an empty card. The Swimmer class from the earlier port comes first, since the card holds a Swimmer instance:

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.