bind 和 var self=this 的区别?

Difference between bind and var self=this?

在我的 React 本机代码中,我在多个模块的多个位置同时使用 bind(this)var self = this;

两者都解决了在正确位置解析 this 关键字的问题。

这是我的代码(执行相同功能的 2 个代码)-

  1. 使用bind(this)

    retval.then(function (argument) {
        console.log("argument"+JSON.stringify(argument));
        this.stateSetting(argument);
    }.bind(this));
    
  2. 使用var self = this

    var self = this;
    retval.then(function (argument) {
       console.log("argument"+JSON.stringify(argument));
       self.stateSetting(argument);
    });
    

考虑到他们都做同样的工作,我很想知道正确的做法是什么?使用一个或另一个有问题吗?或者有更好的方法吗?

鉴于您的目标是实现 ES2015 的 Node.js,您最好使用箭头函数。 创建函数时,箭头函数具有所谓的 lexical this, which means that the variable this in an arrow function is treated like a normal variable and will be closed over

因此您的代码变为:

retval.then((argument) => {
    console.log("argument"+JSON.stringify(argument));
    // "this" will inherit the value of the outside scope
    this.stateSetting(argument); 
});

如果以 ES5(旧版浏览器)为目标,那么我更喜欢 .bind 风格而不是 var self = this。它更加结构化并且更接近函数式方法,这使得代码更容易推理,就像您必须通过使用承诺发现的那样。好像也是slightly more performant.