This article is a part of the systemic-ts series.
complication
complication

Source of Complication: Class Unbound Method

The method of class has a particular issue for being unbound with its object.

Consider this class:

class Person {
  hobbies = ["cooking", "fishing", "gaming"];

  printHobbies() {
    this.hobbies.forEach(console.log);
  }
}

When printHobbies of a Person is called, all strings within hobbies will be printed. That much is clear.

new Person().printHobbies();
// "cooking"
// "fishing"
// "gaming"

However, when printHobbies is detached from the object and then is called, a curious problem arises.

const printHobbies = new Person().printHobbies; // detach
printHobbies(); // call
// Uncaught TypeError: Cannot read properties of undefined (reading 'hobbies')
// at printHobbies (<anonymous>:5:10)
// at <anonymous>:1:1

This simple problem wasted a lot of time, especially in projects that use a lot of callback parameters---which is the heart of JavaScript's reactive programming.

TypeScript does not fix this problem since its core principle is to provide a strict "superset"---writing a code in TypeScript must yield the same result as if it were written in JavaScript.

Several workarounds can be found on the internet.

class Person {
  hobbies = ["cooking", "fishing", "gaming"];
  printHobbies = () => {
    this.hobbies.forEach(console.log);
  };
}
// OR
class Person {
  constructor() {
    this.printHobbies = this.printHobbies.bind(this);
  }
  hobbies = ["cooking", "fishing", "gaming"];
  printHobbies() {
    this.hobbies.forEach(console.log);
  }
}
// OR when passing the method
const printHobbies = person.printHobbies.bind(person);

But those workarounds are tedious and beginners will make the same mistake because this is not how JS class are intended to be written per its specification.

Also, the fact that there are several workarounds will later create a multilemma over which solution is the best; people will start to argue over this unimportant thing.

The big question is: Why a partially broken feature is provided and used at all?

complication
complication