The trick is that map accepts a second argument, which is going to be the this context.
In short it does the same as:
addressParts.map(x => x.trim());
But you don't create a new object (a function in this case) !!!. Yeah, probably not a valid reason to do that shit in some code, but there is merit to it, it is clever.
Just to understand:
When you pass your callback to map, it gets called like this:
callback.call(thisArg, value)
But generally we never pass the third argument (thisArg), so what matters to us is callback(value). That said, we can abuse this. Let's make the substitutions for this scenario:
Notice the double call? That's the magic right there. The call functions executes other function with a different context (this). Now, the double call makes we create the String.prototype.trim be the context of the first Function.prototype.call...Which means we are doing: String.prototype.trim.call(value)
4
u/GBcrazy Mar 19 '19 edited Mar 19 '19
I saw this some time ago and I found it clever as hell (even a bit hard to understand at first):
addressParts.map(Function.prototype.call, String.prototype.trim);The trick is that
mapaccepts a second argument, which is going to be thethiscontext.In short it does the same as:
addressParts.map(x => x.trim());But you don't create a new object (a function in this case) !!!. Yeah, probably not a valid reason to do that shit in some code, but there is merit to it, it is clever.
Just to understand:
When you pass your callback to map, it gets called like this:
callback.call(thisArg, value)But generally we never pass the third argument (thisArg), so what matters to us is
callback(value). That said, we can abuse this. Let's make the substitutions for this scenario:Function.prototype.call.call(String.prototype.trim, value)Notice the double
call? That's the magic right there. The call functions executes other function with a different context (this). Now, the double call makes we create theString.prototype.trimbe the context of the firstFunction.prototype.call...Which means we are doing:String.prototype.trim.call(value)Full and better explanation here