2016-11-13 42 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)); } 
相關問題