为什么“这个"?指的是 javascript 中 forEach 中的窗口? [英] Why "this" refers to Window in forEach in javascript?

查看:34
本文介绍了为什么“这个"?指的是 javascript 中 forEach 中的窗口?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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);
});

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

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 在迭代器中指定 this 的值.

.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); // <---

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

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)

<小时>

尽管如此,arr 仍然提供给迭代器,就像它的第三个参数一样:


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

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

这篇关于为什么“这个"?指的是 javascript 中 forEach 中的窗口?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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