【发布时间】:2020-04-07 12:14:48
【问题描述】:
我非常困惑在 forEach 循环中为什么 THIS 会指向 obj。
我假设将输出 return this.id is undefined ,因为它在词法函数中调用。 THIS 会将其指向窗口。
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);
【问题讨论】:
-
您明确告诉它使用
obj作为this。这就是forEach的第二个参数是 for。 -
在forEach方法里面,第二个参数应该是数组的Index。为什么 Object 变量可以在第二个参数中使用?
-
请看forEach syantax developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… 第一个参数是回调函数,第二个参数是执行回调时this的值。
-
太棒了。共享 forEach 语法规则。
标签: javascript this scopes