Skip to content

Instantly share code, notes, and snippets.

@rauschma
Created January 13, 2022 17:24
Show Gist options
  • Save rauschma/0b5e4e71eaecf6af2089ef6fdf2ffa6a to your computer and use it in GitHub Desktop.
Save rauschma/0b5e4e71eaecf6af2089ef6fdf2ffa6a to your computer and use it in GitHub Desktop.

Cheat sheet: classes

A JavaScript class:

class Person {
  constructor(firstName) { // (A)
    this.firstName = firstName; // (B)
  }
  describe() { // (C)
    return 'Person named ' + this.firstName;
  }
}
const tarzan = new Person('Tarzan');
assert.equal(
  tarzan.firstName, 'Tarzan'
);
assert.equal(
  tarzan.describe(),
  'Person named Tarzan'
);

Explanations:

  • Inside a class, this refers to the current instance
  • Line A: constructor of the class
  • Line B: Property .firstName (a public slot) is created (no prior declaration necessary).
  • Line C: method .describe()

Public instance data such as .firstName is relatively common in JavaScript.

The same class Person, but with private instance data:

class Person {
  #firstName; // (A)
  constructor(firstName) {
    this.#firstName = firstName; // (B)
  }
  describe() {
    return 'Person named ' + this.#firstName;
  }
}

Explanations:

  • Line A: private field .#firstName. In contrast to properties, private fields must be declared (line A) before they can be used (line B). A private field can only be accessed inside its surrounding class. It can’t even be accessed by subclasses.

Class Employee is a subclass of Person:

class Employee extends Person {
  #title;

  constructor(firstName, title) {
    super(firstName); // (A)
    this.#title = title;
  }
  describe() {
    return `${super.describe()} (${this.#title})`; // (B)
  }
}

const jane = new Employee('Jane', 'CTO');
assert.equal(
  jane.describe(),
  'Person named Jane (CTO)'
);
  • Line A: In subclasses, we can omit the constructor. If we don’t, we have to call super().
  • Line B: We can refer to overridden methods via super.

The next class demonstrates how to create properties via public fields (line A):

class StringBuilderClass {
  string = ''; // (A)
  add(str) {
    this.string += str;
    return this;
  }
}

const sb = new StringBuilderClass();
sb.add('Hello').add(' everyone').add('!');
assert.equal(
  sb.string, 'Hello everyone!'
);

JavaScript also supports static members, but external functions and variables are often preferred.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment