Array.map and lifted functions in Javascript

孤街浪徒 提交于 2019-12-08 03:40:29

问题


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 );

回答1:


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.




回答2:


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




回答3:


'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.



来源:https://stackoverflow.com/questions/27776631/array-map-and-lifted-functions-in-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!