Using arrow function to define a method

kayut

Kayut

Posted on January 18, 2019

Using arrow function to define a method

Hi,

I started learning React and right now I'm a bit confused about where to use Arrow-function to define a method and where not to use it.

First let's check object literals

This code works:

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

person.score(); // Works

But the bellow code doesn't work, because we defined the score() method as an arrow-function:

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

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

Take away: Never define methods in an object literal via arrow-function.
Is the above statement correct?

What about JavaScript classes?

This code works:

class Dog {
    constructor(name, bread) {
        this.name = name;
        this.bread = bread;
    }

    bark() {
        return `Bark Bark! My name is ${this.name}`;
    }
}
const mini = new Dog('Mini', 'Spitz');
mini.bark();

And the bellow code, which uses arrow-function syntax to define the bark() method works too:

class Dog {
  constructor(name, bread) {
    this.name = name;
    this.bread = bread;
    this.bark = () => {     // Arrow function
      return `Bark Bark! My name is ${this.name}`;
    }
  }
}
const mini = new Dog('Mini', 'Spitz');
mini.bark();

Take away: It's fine to define methods in a Class via arrow-function.

Is the above statement correct?

What about React classes (class components)?

It is even recommended to use arrow-functions for defining methods inside React classes as a way to create "auto-binding" methods, e.g. methods that could be used by event handlers but that stayed bound to the class.

Is the above statement correct?

💖 💪 🙅 🚩
kayut
Kayut

Posted on January 18, 2019

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related