Is there any disadvantage to make all the instance methods an arrow function, to avoid lost bindings?

Is there any disadvantage to make all the instance methods an arrow function? This way, we don’t have the "lost binding" issue.

So for example, the following has the lost binding issue. We don’t usually write code to invoke this.foo() this way, but in ReactJS, for example, we use onClick={this.foo}, which translates to createElement({ ..., onclick: this.foo, ...}), so there is lost binding right there.

class Dog {

    constructor(name) {
        this.name = name;
    }

    giveSound() {
        console.log(`${this.name} says woof`);
    }

    giveAlert() {
        console.log("I am alert");
        const f = this.giveSound;
        f();
    }

}

const woofie = new Dog("woofie");

woofie.giveSound();

woofie.giveAlert();

So if everything is an arrow function, then there is no such worry:

class Dog {

    constructor(name) {
        this.name = name;
    }

    giveSound = () => {
        console.log(`${this.name} says woof`);
    }

    giveAlert = () => {
        console.log("I am alert");
        const f = this.giveSound;
        f();
    }

}

const woofie = new Dog("woofie");

woofie.giveSound();

woofie.giveAlert();

But is there any disadvantage?

42 thoughts on “Is there any disadvantage to make all the instance methods an arrow function, to avoid lost bindings?”

Leave a Comment