在forEach()中使用`this` [英] Using `this` in a forEach()

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

问题描述

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

(Disclaimer: I'm in the process of learning JavaScript) I have an object constructor like so:

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"指向全局对象,而不是Palette实例.

After some research I realize now that this doesn't work because in the inner anonymous functions, "this" points to the global object and not the Palette instance anymore.

我的问题是,处理此问题的"JavaScript方式"是什么?我看到通过Apply,Bind,Call或简单地将 this 分配给变量,但到目前为止,我还没有找到任何示例来说明内部匿名函数中始终引用 this 的最佳方法.

My question is, what is the "JavaScript way" to deal with this? I see similar problems solved with Apply, Bind, Call or simply assigning this to a variable, but so far I've not found any examples of which way is consistently best practice for referencing this in inner anonymous functions.

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

here is the JsFiddle. (I modified it to output to a div for easier text copying)

推荐答案

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

Pass this as the second parameter to forEach

arr.forEach(callback, thisArg);

每个 MDN文档:

thisArg :
可选的.执行回调时用作此值.

thisArg:
Optional. Value to use as this when executing callback.

我已经更新了小提琴以显示其用法,但是要点是改变了它致电:

I've updated your fiddle to show it's usage, but the gist is change this call:

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 方法也支持此惯用语,包括:

Also of note is that many other Array.prototype methods that accept a callback also support this idiom, including:

  • forEach
  • 地图
  • 每个
  • some
  • 过滤器

但是,如果您只需要在调用函数时指定此 this 绑定的对象,并且该 not 函数未设置为对象的属性,则可能最惯用的方法是使用 Function.prototype.call() Function.prototype.apply().

However, if you just need to specify what this is bound to when calling a function, and that function is not set as a property on the object, then probably the most idiomatic way would be with Function.prototype.call() or Function.prototype.apply().

如果您可以使用ES6,那么箭头功能会更好,因为它从调用上下文继承了 this :

And if ES6 is available to you, then an arrow function would be even better, as it inherits this from the calling context:

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

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

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