5 ms·
Take care with this technique. We know that `Array.prototype.map` passes not one but three parameters to the callback function: the array element, the array ind
by amptorn 9y ago
Take care with this technique. We know that `Array.prototype.map` passes not one but three parameters to the callback function: the array element, the array index and the array itself. As a result of this,
addressParts.map(Function.prototype.call, String.prototype.trim)
is roughly equivalent to
addressParts.map((str, i, arr) => str.trim(i, arr))
Fortunately for us, `String.prototype.trim` ignores those additional parameters and only uses `this`. But if it didn't, you could end up with some head-scratching behaviour.
- partycoder 9y agoIf you wish you verify why is this, consider the following. Forget about String.prototype.trim at the moment. Consider this function: const f = function() { console.log('receiver is', this, '. arguments are', arguments) } This function prints the receiver (aka "this"), and arguments. If you use it in the following way: ['a', 'b', 'c'].map(Function.prototype.call, f) The output is receiver is [String: 'a'] . arguments are { '0': 0, '1': [ 'a', 'b', 'c' ] } receiver is [String: 'b'] . arguments are { '0': 1, '1': [ 'a', 'b', 'c' ] } receiver is [String: 'c'] . arguments are { '0': 2, '1': [ 'a', 'b', 'c' ] } Meaning, that the receiver (aka "this") of the function will be the array element, and the arguments will be the array index and the array itself.