Porting a Class to constructor and this

Riverside Pool’s booking module starts with its simplest class. Pass remembers whose pass it is and how many swims they’ve had, and it checks a swimmer in at the desk. Every other pass in pool_passes.py builds on it, so it’s the first class to move to JavaScript.

Ported line by line, a Python class gives you something that looks like valid JavaScript. One Python habit doesn’t survive the trip, though, and it’s the one you type in every method. In this lesson, you’ll port Pass and see what JavaScript uses in place of self.

Port Pass Line by Line

Here’s the Python class, with Priya Nair checking in for her first swim:

Language: Python
class Pass:
    def __init__(self, holder):
        self.holder = holder
        self.swims = 0

    def check_in(self):
        self.swims += 1
        return f"{self.holder} checked in, swim {self.swims}"

priya = Pass("Priya Nair")
print(priya.check_in())

Python prints Priya Nair checked in, swim 1. Much of this carries over to JavaScript unchanged. A class starts with the class keyword and a PascalCase name, and its methods sit in the body, so the port keeps all three features.

Four things are written differently. The body sits in braces because JavaScript doesn’t read indentation, and each method is only its name, parameters, and braced body, with no def or function. The braces don’t make it an object literal, so a comma between methods is a SyntaxError. The initializer is called constructor, and you make an instance by putting new before the class name.

Rename check_in to camelCase and turn the f-string into a template literal, as usual. Keep self everywhere it was, and you get this port:

Language: JavaScript
class Pass {
  constructor(self, holder) {
    self.holder = holder;
    self.swims = 0;
  }

  checkIn(self) {
    self.swims += 1;
    return `${self.holder} checked in, swim ${self.swims}`;
  }
}

const priya = new Pass("Priya Nair");
console.log(priya.checkIn());

Before you run it, predict what self holds inside the constructor. Python would hand it the new instance. JavaScript stops before Priya ever checks in (Node’s source line and stack trace are left out here):

Language: Program Output
TypeError: Cannot create property 'holder' on string 'Priya Nair'

Read the error closely. JavaScript tried to set holder on the string "Priya Nair", so the string must have landed in self. JavaScript never passes the instance as an argument. The arguments of new Pass("Priya Nair") fill the parameters from the left, and self is first in line. That leaves holder as undefined and the new instance untouched.

The method has the same problem. Called with no arguments, checkIn(self) gets undefined for self, and self.swims += 1 fails with TypeError: Cannot read properties of undefined (reading 'swims').

Write this Where Python Writes self

The instance still reaches every method, but not through the parameter list. JavaScript hands it over as this, a keyword that’s available inside the constructor and every method without being declared. So the fix is to drop self from the parameters and write this. wherever Python writes self.:

Language: JavaScript
class Pass {
  constructor(holder) {
    this.holder = holder;
    this.swims = 0;
  }

  checkIn() {
    this.swims += 1;
    return `${this.holder} checked in, swim ${this.swims}`;
  }
}

const priya = new Pass("Priya Nair");
console.log(priya.checkIn());
console.log(priya);

Now Priya checks in, and logging the pass shows what’s inside it:

Language: Program Output
Priya Nair checked in, swim 1
Pass { holder: 'Priya Nair', swims: 1 }

In priya.checkIn(), this is priya, the object before the dot in the call, as self is priya in Python’s priya.check_in(). That analogy holds when you call an ordinary method like checkIn() as object.method(), which covers everything in this lesson. It has limits, and a later lesson shows where they are. In the constructor, this is the brand-new instance that new creates, and new hands it back once the constructor finishes.

console.log(priya) is also friendlier than Python’s print(priya), which shows only <__main__.Pass object at 0x...>. Node’s console prints the class name and, here, both properties the constructor sets.

Make a Pass for Tom

Tom Hale is next at the desk, so he needs a pass of his own. Python would make it with Pass("Tom Hale"). Watch out here, because JavaScript needs new too, and calling the class without it stops with TypeError: Class constructor Pass cannot be invoked without 'new'.

Create Tom’s pass with new:

Language: JavaScript
class Pass {
  constructor(holder) {
    this.holder = holder;
    this.swims = 0;
  }

  checkIn() {
    this.swims += 1;
    return `${this.holder} checked in, swim ${this.swims}`;
  }
}

const priya = new Pass("Priya Nair");
const tom = new Pass("Tom Hale");
console.log(priya.checkIn());
console.log(tom.checkIn());
console.log(priya.checkIn === tom.checkIn);
console.log(typeof Pass);

Priya and Tom both reach swim 1 because the constructor sets each pass’s properties on its own instance:

Language: Program Output
Priya Nair checked in, swim 1
Tom Hale checked in, swim 1
true
function

The method, though, is written once in the class and shared, as in Python, so priya.checkIn and tom.checkIn are the same function. Unlike Python, JavaScript doesn’t attach priya when you look the method up, so priya.checkIn is the bare function.

The last line shows that typeof Pass is "function". What a class is underneath gets a course of its own later on.

So a JavaScript developer writes a class with a constructor that sets each property on this, methods that never list the instance as a parameter, and new at every call that makes an instance. Then this. goes wherever your Python code uses self..

Pass is a plain class, but the module’s Swimmer is a dataclass, and JavaScript has no @dataclass. In the next lesson, Porting a Dataclass to Fields and a Constructor, you’ll port Swimmer with fields in the class body and find out why those fields don’t replace a constructor.

Become a Member to join the conversation.