DEV Community

Discussion on: Typical JavaScript interview exercises (explained)

Collapse
 
maxart2501 profile image
Massimo Artizzu

This is dirty, right? 🤠

Maybe, but explain why. The second version has been used ad nauseam by React developers who had to bind the component's prototype methods to the component's instance in order to use them nicely in their JSX templates.

The real ugliness here is that object methods lose their context so easily - but it's also one of the best part of JavaScript, since this makes functions as first class objects.

Which means I can do something like this:

class Cat() {
  meow() { ... }
}
const mittens = new Cat('Mittens');
mittens.bark = fido.bark;
mittens.bark(); // 'Mittens says woof'

You already got good answers for your final question 🙂