【问题标题】:Using `this` in a forEach() [duplicate]在 forEach() 中使用 `this` [重复]
【发布时间】:2015-10-22 19:32:26
【问题描述】:

(免责声明:我正在学习 JavaScript) 我有一个像这样的对象构造函数:

var Palette = function() {
    this.colors = ["red", "green", "blue"];
    this.getColorCombinations = function() {
        var combos = [];
        this.colors.forEach(function(a) {
            this.colors.forEach(function(b) {
                if(a !== b) {
                    combos.push([a, b]);
                }
            });
        });
        return combos;
    };
}

var p = new Palette();
alert(JSON.stringify(p.getColorCombinations()));

预期输出:

[["red","green"],["red","blue"],["green","red"],["green","blue"],["blue","red"],["blue","green"]]

经过一些研究,我现在意识到 this 不起作用,因为在内部匿名函数中,“this”指向全局对象,而不是 Palette 实例了。

我的问题是,处理这个问题的“JavaScript 方式”是什么?我看到类似的问题可以通过 Apply、Bind、Call 或简单地将 this 分配给变量来解决,但到目前为止我没有找到任何示例说明在内部匿名函数中引用 this 始终是最佳实践。

here 是 JsFiddle。 (我将其修改为输出到 div 以便于文本复制)

【问题讨论】:

标签: javascript foreach


【解决方案1】:

this作为第二个参数传递给forEach

arr.forEach(callback, thisArg);

MDN Documentation:

thisArg:
选修的。执行回调时用作 this 的值。

我已经 updated your fiddle 显示它的用法,但要点是更改此调用:

this.colors.forEach(function(a) {
    this.colors.forEach(function(b) {
        if(a !== b) {
            combos.push([a, b]);
        }
    });
});

到这里:

this.colors.forEach(function(a) {
    this.colors.forEach(function(b) {
        if(a !== b) {
            combos.push([a, b]);
        }
    });
}, this); // <- pass this as second arg

还需要注意的是,许多其他接受回调的Array.prototype 方法也支持这种习惯用法,包括:

  • forEach
  • map
  • every
  • some
  • filter

但是,如果您只需要在调用函数时指定this 绑定的对象,并且该函数设置为对象的属性,那么可能最惯用的方式是与Function.prototype.call()Function.prototype.apply() 在一起。

如果你可以使用 ES6,那么箭头函数会更好,因为它从调用上下文继承 this

this.colors.forEach(a => {
    this.colors.forEach(b => {
        if(a !== b) {
            combos.push([a, b]);
        }
    });
});

【讨论】:

    猜你喜欢
    • 2014-08-15
    • 1970-01-01
    • 2017-05-29
    • 2017-04-27
    • 1970-01-01
    • 2010-10-09
    • 2011-10-10
    • 1970-01-01
    相关资源
    最近更新 更多