Search code examples
javascriptecmascript-6

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


Solution

  • 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));
        }
    }