Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
468 views
in Technique[技术] by (71.8m points)

javascript - Can't use String#trim as a callback for Array#map

For some reason I can't use String.prototype.trim.call as a callback for array methods, such as map or filter.

In this case, two functions work the same:

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

var string = ' A ';

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

However, when I try to pass them as a callback for an array method, second one fails:

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

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

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

I assume in a latter case that this doesn't point to an array element, but I would like to get clear explanation of what's happening.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
String.prototype.trim.call(string); // 'A'
array.map(String.prototype.trim.call); // TypeError: undefined is not a function

When you invoke the call method in the first case, its this value is bound to the String.prototype.trim function. In the second case, you just access the call function without having it bound to anything - you could just have used

array.map(Function.prototype.call)

This method is getting invoked with nothing as the this value, the element from your array, the index and the whole array as parameters. When you call call not on a function, it throws. You can either use the second parameter of map or the bind method to fix the this value for the call:

array.map(Function.prototype.call, String.prototype.trim)
array.map(Function.prototype.call.bind(String.prototype.trim))

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...