javascript - 为什么 THIS 指向 obj?
问题描述
我非常困惑在 forEach 循环中为什么 THIS 会指向 obj。
我假设将输出 return this.id is undefined,因为它在词法函数中调用。这会将其指向窗口。
function foo(el) {
console.log( el, this.id);
}
var obj = {
id: "awesome"
};
[1, 2, 3].forEach( foo, obj );
// 1 "awesome" 2 "awesome" 3 "awesome"
// Easy way to check
[1, 2, 3].forEach( function(el){
console.log( el, this.id);
}, obj);
解决方案
的第二个参数Array.prototype.forEach
是thisArg
. 请参阅https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach其中指出:
如果为 forEach() 提供了 thisArg 参数,它将用作回调的 this 值。
推荐阅读
- sql - SQL Server 删除字符之间的部分字符串
- python - Telebot,如何将来自用户的消息保存到变量中?
- c# - 如何检查玩家与 Unity 中特定 TileBase 对象之间的碰撞?
- slack - 如何向我的工作区中的松弛用户发送批量即时消息?
- authentication - 创建 Cloud Build 触发器的身份验证问题
- git - 用于量角器测试的 Jenkins 和 Zephyr 集成
- javascript - ffmpeg Image2pipe 命令从 PhantomJS 获取图像流时无限卡住
- excel - 存储行的值(从 i 到 n)以供稍后在代码中使用的正确方法是什么?(VBA查找/匹配功能)
- qt - 如何在 Qt 应用程序中隐藏鼠标光标?
- delphi - 无法在“内部 SD 卡”上创建目录