为什么"本"是指窗的forEach在JavaScript? [英] Why "this" refers to Window in forEach in javascript?

查看:161
本文介绍了为什么"本"是指窗的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?

推荐答案

<一个href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach\"相对=nofollow> .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); // <---

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

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

这篇关于为什么&QUOT;本&QUOT;是指窗的forEach在JavaScript?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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