Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to replace `bind(this)` in es6

I read some codes:

class XXXX {
  init() {
    MyOBJ.on('EVENTNAME', this.myfunction.bind(this)); // Line3, MyOBJ extends EventEmitter
  }
}

Just curious how to use arrow function to replace Line3? Thanks

like image 980
BAE Avatar asked Feb 08 '18 21:02

BAE


2 Answers

Function.prototype.bind creates a new function that, when called, has its this keyword set to the provided value, with a given sequence of arguments preceding any provided when the new function is called.

What this specific example - this.myFunction.bind(this) - achieves, is to be able to pass a reference to a function (that happens to also be referenced by this.myFunction) while making sure that any calls to that function are done in the context of this.

In ES2015+ we can do this:

class XXXX {
    init() {
        MyOBJ.on('EVENTNAME', (event) => this.myfunction(event));
    }
}

With ES2015 arrow functions this will inside the body be the declaration context of the arrow function. So in our case this.myFunction gets called in an arrow function whose context is the context of the call to init(), a.k.a. this within init.

The key difference is that now you actually create a call expression instead of just passing a reference to the function. This time the reference given to MyOBJ.on is the arrow function.

A strict ES5 equivalent to the snippet above would also use a function literal as callback given to MyOBJ.on:

class XXXX {
    init() {
        MyOBJ.on('EVENTNAME', function(event) {
            this.myfunction(event));
        }.bind(this));
    }
}
like image 160
JJWesterkamp Avatar answered Oct 08 '22 13:10

JJWesterkamp


Replace this

this.myfunction.bind(this)

to this

() => {}

Your event binding would look as follow:

class XXXX {
  someMethod() {}
  init() {
    MyOBJ.on('EVENTNAME', () => {
        this.someMethod(); // The originating context it's actually your class XXXX
    });
  }
}

Resource

  • Javascript ES6 — Arrow Functions and Lexical this

    One of the most anticipated new features in the ES6 Javascript standard was the Arrow Function Expression. It promises a shorter syntax than it’s predecessor the Function Expression. In addition is how the new Arrow Function binds, or actually DOES NOT bind it’s own this. Arrow Functions lexically bind their context so this actually refers to the originating context.

like image 30
Ele Avatar answered Oct 08 '22 13:10

Ele