loading...

re: Using arrow function to define a method VIEW POST

FULL DISCUSSION
 

The lamda function, aka the fat arrow has one unique property that separates itself from a normal function. The lamda does not bind the object which called it to the this keyword. A normal javascript function binds the caller to the this keyword.

const person = {
  points: 23,
  score: () => {     // Arrow function
    return this.points++;
  }
};

person.score(); // Doesn't work

That is why this example doesn't work, the lamda has context of what this is.

Now, if you like the syntax of the lamda function, you can explicitly bind an object to the this value by using the .bind() method.

const person = {
  points: 23,
  score: () => {     // Arrow function
    return this.points++;
  }.bind(person),
};

person.score(); // works

There are most likely many who could explain the concept way better then I can. Hope that helps.

In regards to your other question about defining functions in the constructor...

In my opinion, I would NOT recommend assigning functions in the constructor of a class unless you were using some sort of thunk pattern. The reason being that every time the class is instantiated, the class has to recreate those functions in memory which is a waste. If you define a function outside of the classes constructor, the function gets attached to the classes prototype chain which is much more efficient.

code of conduct - report abuse