如何在es6中替换`bind(this)` [英] how to replace `bind(this)` in es6

查看:256
本文介绍了如何在es6中替换`bind(this)`的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我读了一些代码:

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

很好奇如何使用箭头功能替换Line3?谢谢

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

推荐答案

Function.prototype.bind 创建一个新函数,该函数在被调用时将其关键字设置为提供的值,并在调用新函数时提供给定的参数序列.

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.

此特定示例-this.myFunction.bind(this)所实现的是,能够传递对函数的引用(碰巧也由this.myFunction引用),同时确保对该函数的所有调用都在this的上下文.

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.

在ES2015 +中,我们可以这样做:

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

在ES2015中,箭头功能this将在内部成为箭头功能的声明 context .因此,在我们的示例中,this.myFunction在箭头函数中被调用,该函数的上下文是对init()的调用的上下文,又称为init中的this.

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.

主要区别在于,现在您实际上创建了一个调用表达式,而不仅仅是将引用传递给该函数.这次给MyOBJ.on的引用是箭头功能.

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.

与上述代码段等效的严格ES5还将使用函数文字作为对MyOBJ.on的回调:

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

这篇关于如何在es6中替换`bind(this)`的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆