什么是在必要时将`this`变成`forEach`回调的首选方法?

use*_*283 1 javascript oop inheritance

我知道这听起来像是一个意见问题,但我是一名初级JavaScript技能人员,并希望了解以下每种方法获得this一个功能的技术优点和缺点(this当然,它有自己的功能).

让我们说我写 - 这是我的一个现实生活中的例子 -

Calculator.prototype.Initialize = function () {
    // Fill in all regions in the RegionsChecked array
    this.Data.forEach(function(region){
        this.RegionsChecked.push(region.RegionName);
    });
    …
Run Code Online (Sandbox Code Playgroud)

我意识到了

"哎呀,thisin this.RegionsChecked应该实际引用Calculator调用Intialize 函数的函数."

我要么通过这样做来解决这个问题

var that = this;
this.Data.forEach(function(region){
    that.RegionsChecked.push(region.RegionName);
});
Run Code Online (Sandbox Code Playgroud)

要么

(function(calc){
    this.Data.forEach(function(region){
        calc.RegionsChecked.push(region.RegionName);
    });
})(this);
Run Code Online (Sandbox Code Playgroud)

我想知道哪个更好或者有更好的方式(以及为什么).

c.P*_*.u1 5

Array.prototype.forEach还接受第二个参数,该参数指定this应该调用回调的值(上下文).

this.data.forEach(function (region) {
  this.regionsChecked.push(region.regionName);
}, this);
Run Code Online (Sandbox Code Playgroud)

更好的选择是使用绑定到词汇this值的ES6箭头函数:

this.data.forEach(region => {
  this.regionsChecked.push(region.regionName);
});
Run Code Online (Sandbox Code Playgroud)

如果ES6不可用,并且该方法不支持this为其回调指定值,则可以将该函数绑定到一个this值:

this.data.forEach(function (region) {
  this.regionsChecked.push(region.regionName);
}.bind(this));
Run Code Online (Sandbox Code Playgroud)