Array.map and lifted functions in Javascript

2019-06-05 16:28发布

How come

var a = "foo /    bar/  baz  ".split('/');

a.map( function (e) { return String.prototype.trim.call(e) } )

works, while this doesn't...

a.map( String.prototype.trim );

3条回答
手持菜刀,她持情操
2楼-- · 2019-06-05 16:57

Try this:

a.map(Function.prototype.call.bind(String.prototype.trim ))

The reason why this works and just mapping String.prototype.trim doesn't work is because, as others have pointed out, the this will be undefined when the function tries to trim the array element. What this solution does is, it creates a new function, which takes as it's this value as the function String.prototype.trim. Since the new function is a modified version of Function.prototype.call, as map calls this function passing it the array element, what essentially gets executed is: Function.prototype.call.call(String.prototype.trim, element). This runs the function String.prototype.trim on the element passed in and you get the trimmed result. This also would work:

 a.map(Function.call, "".trim)

by taking advantage of the fact that the second argument to map accepts the thisArg. For a little bit of syntactic sugar, you can make a function that looks like this:

Array.prototype.mapUsingThis = function(fn) { return this.map(Function.call, fn); };

Then, you could just invoke

a.mapUsingThis("".trim)

like that.

查看更多
我只想做你的唯一
3楼-- · 2019-06-05 17:03

'this' refers to the string param in the first case whereas in the second case, 'this' becomes undefined as String.prototype.trim is not bound to any object.

查看更多
我欲成王,谁敢阻挡
4楼-- · 2019-06-05 17:05

String.prototype.trim is a non params function, it will be called by string itself, but map function need a func arg accept a str as params

查看更多
登录 后发表回答