2016-11-13 82 views
-2

这里我有一个数组数组。我试图测试Array.prototype.forEach是否可以以不同于传统方式的方式在阵列上使用。按照传统的方式,我们将这个参数作为第二个参数传递给forEach
这里我使用了Array.prototype.forEach.call(),为此我使用数组作为参数来调用方法。
但这表示窗口对象。
这是为什么?为什么调用array.prototype.forEach.call()将数组设置为THIS对象不起作用

number=[1,2,3,4,5]; 

Array.prototype.forEach.call(number,function(elem){ 
    console.log(this); 
}); 
+1

你期望'this'是回调中:通常情况下,如果一个对象的方法被作为回调传递,但它使用?您将用于回调的'thisArg'与'forEach'的调用相混淆。 – 2016-11-13 07:49:48

回答

2

因为假设forEach还没有被覆盖,并且该阵列仍具有正常原型,这样:

Array.prototype.forEach.call(number,function(elem){ }); 

无异:

number.forEach(function(elem){ }); 

forEach回调函数,除非您通过thisArg,否则该函数将被调用为正常回调。

From MDN

如果thisArg参数被提供给forEach(),它会被传递到callback调用时,用作其this值。否则,值undefined将被传递以用作其this值。 callback最终可观察到的this值根据the usual rules for determining the this seen by a function确定。

要设置thisArg同时使用.call,你需要通过一个多参数:

Array.prototype.forEach.call(number,function(elem){ }, number); 
0

根据MDN

如果thisArg参数被提供给的forEach(),它会通过调用时,用作其该值来回调。否则,未定义的值将被传递以用作其值。 通过回调最终可观察到的此值根据the usual rules for determining the this seen by a function确定。

在下面的片段中,我们明确地传递作为thisArgnumber,我们必须为你正在寻找的结果。

number=[1,2,3,4,5]; 
 

 
Array.prototype.forEach.call(number,function(elem){ 
 
    console.log(this); 
 
},number);

+0

但是为什么我要在这种情况下传递'this',因为我可以将数组作为回调函数的第三个参数? – 2016-11-13 07:50:55

+0

@torazaburo ofcourse因为如果你没有指定它并且你想使用它的话,这个值就会不同。 – Christos

0

是的,我知道,回调到元素的值内jQuery的$.eachthis。但这不是Array#forEach的工作原理。相反,通常不会设置this,除非指定了第二个thisArg参数。

number=[1,2,3,4,5]; 

Array.prototype.forEach.call(number, function(elem) { 
    console.log(elem); 
       ^^^^ Access element via parameter, not `this` 
}); 

如果由于某种原因,你通过一些this步入回调,然后将其指定为另一个参数forEach,在其他的答案中提到这一点很重要。这this将在每个调用回调相同;它与当前的迭代无关。

Array.prototype.forEach.call(
    number, 
    function(elem) { 
    console.log("Inside callback, this is", this); // 42 
    console.log(elem); 
    }, 
    42); 

使用thisArg并不常见。

obj = { 
    vals: [1, 2, 3], 
    message: "the value is", 
    alert(x) { alert(this.message + x); }, 
    alertVals() { this.vals.forEach(this.alert, this); } 
}; 

obj.alertVals(); 

这是一种替代方法之一

alertVals() { vals.forEach(this.alert.bind(this)); } 
alertVals() { vals.forEach(elt => this.alert(elt)); } 
相关问题