为什么"本"是指窗的forEach在JavaScript?

问题描述:

如果我运行这个code,窗口对象被打印到控制台。

If I run this code, window object gets printed to console.

var arr= [1,2,34,5,6,7,7,8];
arr.forEach(function(e){
console.log(this);
});

为什么它不是指在常用3数组对象对象或特定项目?我想了解它背后的原因,就像发生了什么事。 这个利用被定义的新,或对象调用这个函数,对吧?

Why does it not refer to arr object or specific items in array object? I want to understand the reason behind it, like what's going on. this gets defined using by new, or the object invoking this function, right?

.forEach() 指定的值这个基于迭代器内它的第二个参数, thisArg

.forEach() specifies the value of this within the iterator based on its 2nd parameter, thisArg.

arr.forEach(callback[, thisArg])

所以,它只会如果你提供给它使用一个特定的对象:

So, it will only use a particular object if you provide it:

arr.forEach(function(e){
    console.log(this);
}, arr); // <---

否则,值这个将是一个正常的函数调用的默认值 - 无论是未定义严格模式或全局对象(窗口)的非严格。

Otherwise, the value of this will be the default value of a normal function call -- either undefined in strict mode or the global object (window in browsers) in non-strict.

function foo(e) {
    console.log(this);
}

foo();            // [object Window]

[1].forEach(foo); // (same)


虽然,改编仍是提供给迭代器,正如它的第三个参数:


Though, the arr is still provided to the iterator, just as its 3rd argument:

arr.forEach(function (e, i, arr) {
    console.log(arr);
});