为什么"this"在javascript中引用forEach中的Window?

Muh*_*mer 3 javascript arrays

如果我运行此代码,则窗口对象将打印到控制台.

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

为什么它不引用数组对象中的arr对象或特定项?我想了解它背后的原因,就像发生了什么.this使用by new或调用此函数的对象来定义,对吗?

Jon*_*ski 6

.forEach()this根据第二个参数指定迭代器中的值thisArg.

arr.forEach(callback[, thisArg])
Run Code Online (Sandbox Code Playgroud)

因此,如果您提供它,它将仅使用特定对象:

arr.forEach(function(e){
    console.log(this);
}, arr); // <---
Run Code Online (Sandbox Code Playgroud)

否则,值this将是普通函数调用的默认值 - undefined在严格模式下或window在非严格模式下在全局对象中(在浏览器中).

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

foo();            // [object Window]

[1].forEach(foo); // (same)
Run Code Online (Sandbox Code Playgroud)

虽然,arr仍然提供给迭代器,就像它的第三个参数:

arr.forEach(function (e, i, arr) {
    console.log(arr);
});
Run Code Online (Sandbox Code Playgroud)