0

When working with Javascript objects, there is a big difference between using Arrow Functions compared to Regular Functions when it comes to this. For instance using a regular function here will properly bind this:

const person = {
  name: "Karen",
  age: 40,
  hi: function() {
    console.log("Hi " + this.name);
  }
}

person.hi() // "Hi Karen"

compared to using an Arrow Function which will incorrectly bind this:

const person = {
  name: "Karen",
  age: 40,
  hi: () => {
    console.log("Hi " + this.name);
  }
}

person.hi() // "Hi "

However, I am not sure if this difference applies when defining class methods. For instance, if I declare two methods - one as arrow function, one as regular function - they both seem to correctly bind this.

class Example {
  constructor() {
    this.values = [1, 2, 3, 4]
  }
  
  arrowMethod = (num) => {
    console.log(this.values.map((item) => item * num));
  }
    
  method(num) {
    console.log(this.values.map((item) => item * num));
  }
}

const example = new Example();
example.arrowMethod(2); // [2, 4, 6, 8]
example.method(2); // [2, 4, 6, 8]

So is there any reason to use one or the other when it comes to class methods?

Espresso
  • 632
  • 9
  • 25

0 Answers0