2014-01-17 20 views
8

出於某種原因,我不能使用String.prototype.trim.call作爲數組方法的回調,如mapfilter無法使用String#trim作爲Array#的回調map

在這種情況下,兩種功能的工作方式相同:

function trim(string) { 
    return string.trim(); 
} 

var string = ' A '; 

trim(string);      // 'A' 
String.prototype.trim.call(string); // 'A' 

然而,當我嘗試將它們通過作爲用於陣列的方法回調,第二個失敗:

var array = [' A', 'B ', ' C ']; 

array.map(trim);      // ['A', 'B', 'C']; 
array.map(String.prototype.trim.call); // TypeError: undefined is not a function 

演示: http://jsbin.com/ubUHiHon/1/edit?js,console

我認爲在後一種情況下,this不指向數組元素,但我想清楚地解釋發生了什麼。

+0

精確複製[使用Javascript - 應用微調功能到每個字符串以陣列](HTTP://計算器。 com/questions/19293997/javascript-apply-trim-function-to-each-string-in-an-an-an-an) - 抱歉我現在已經回答了兩次:-) – Bergi

+0

@Bergi看起來像是這樣,對不起。但是,正如你所想象的,幾乎不可能找到一個(我真的花了15分鐘)。我試圖讓標題儘可能地一般和準確。 – Pavlo

+0

此問題的一個優雅解決方案是ES6箭頭函數:'array.map(s => s.trim());'。 – Pavlo

回答

9
String.prototype.trim.call(string); // 'A' 
array.map(String.prototype.trim.call); // TypeError: undefined is not a function 

當你調用在第一種情況下call方法,其this value綁定到String.prototype.trim功能。在第二種情況下,你只需訪問call功能,而無需其綁定到任何東西 - 你可以只使用了

array.map(Function.prototype.call) 

此方法得到調用什麼也沒有爲this值,從你的陣列,索引和整個數組作爲參數。當你打電話給call時,它會拋出。既可以使用的mapbind method的第二個參數固定爲callthis值:的

array.map(Function.prototype.call, String.prototype.trim) 
array.map(Function.prototype.call.bind(String.prototype.trim)) 
相關問題