AL-*_*ami 0 javascript arrays foreach this
这里我有一个数字数组。我试图测试是否Array.prototype.forEach可以以与传统方式不同的方式在阵列上使用。在传统方式中,我们将 THIS 参数作为第二个参数传递给forEach.
在这里我使用Array.prototype.forEach.call(),为此我使用数组作为调用方法的参数。
但这表明window对象。
这是为什么 ?
number=[1,2,3,4,5];
Array.prototype.forEach.call(number,function(elem){
console.log(this);
});
Run Code Online (Sandbox Code Playgroud)
因为假设forEach没有被覆盖,而且这个数组还有正常的原型,这个:
Array.prototype.forEach.call(number,function(elem){ });
Run Code Online (Sandbox Code Playgroud)
无异于:
number.forEach(function(elem){ });
Run Code Online (Sandbox Code Playgroud)
在forEach回调函数中,除非您传递 ,否则thisArg函数会像普通回调一样被调用。
如果
thisArg提供了一个参数forEach(),它将callback在调用时传递给,用作其this值。否则,该值undefined将被传递以用作其this值。this最终 observable by的值callback是根据用于确定函数看到的 this 的通常规则确定的。
要设置thisArgwhile using .call,您需要再传递一个参数:
Array.prototype.forEach.call(number,function(elem){ }, number);
Run Code Online (Sandbox Code Playgroud)