Javascript Ninja:数组中的当前元素作为函数上下文

Javascript Ninja: Current element in array as function context

我正在努力思考第 57 页 Javascript 忍者中的一些代码。

function forEach(list, callback) {
    for (var n = 0; n < list.length; n++) {
        callback.call(list[n], n); //makes the current element the function context of callback???
    }
}

var weapons = ['shuriken', 'katana', 'nunchucks'];

forEach(weapons,
    function(index) {
        assert(this == weapons[index], "Got the expected value of " + weapons[index]);
    }
);

我可以在不使用 call 方法的情况下在回调中传递数组的索引,这是有道理的。我不明白的是为什么我要使用当前元素作为函数上下文。这是要完成什么?

我也很难理解如何做到这一点。我假设调用方法将列表项视为对象而不是数组中的元素。但我不确定这是否正确。

我的另一个想法是,通过不将函数上下文分配给当前元素,函数上下文将是 forEach 函数。我不确定如果有的话会导致什么麻烦,也许这与更改函数上下文的原因有关。

What I don't understand is why would I want to use the current element as the function context.

这允许您在回调函数中使用 this 来引用每个相应的当前元素。这与 jQuery $.each() 方法和其他一些 jQuery 方法使用的约定相同(您的书的作者是 jQuery 的作者)。

它允许你这样做:

forEach([1, 2, 3], function() {
    console.log(this * 2);      // 'this' refers to the current element
});

输出:

2
4
6

当然,另一种非常好的方法是将当前元素作为参数传入,而不指定函数上下文。这就是内置 Array.prototype.forEach 所做的(本质上)。该方法的简化版本如下所示:

function forEach(list, callback) {
    for (var i = 0; i < list.length; i++) {
        callback(list[i], i);
    }
}

forEach([1, 2, 3], function(item) {
    console.log(item * 2);   // 'item' is the current element
});

这两种方法都没有明显优于另一种方法。只是有些人发现使用 this 更方便。

I also am having a hard time understanding how this could be done. I'm assuming that the call method is looking at the list item as an object and not as the element in the array. But I'm not sure that's correct.

传递给 call() 的函数上下文可以是任何东西。它只是确定函数执行时 this 所采用的值( 大多数 的时间)。

My other thought was that by not assigning the function context to the current element the function context would be the forEach function.

不,如果这里没有指定函数上下文,在严格模式下它将是null,或者在怪异模式下是window(假设代码在浏览器中是运行) .两者都不会在这里特别有用。

I'm not sure what trouble that would cause if any and maybe that had something to do with the reason for changing the function context.

如果有人试图以任何有意义的方式在他们的回调中使用 this,它只会造成麻烦。改变它的原因是我上面解释的。