Recently, I've been revisiting my understanding of how to use call()
and map()
with a NodeList
in JavaScript.
It was quite easy to find information on how call()
works, and there are plenty of examples of how it can be used with map()
.
However, while browsing through MDN, I discovered that the map()
function can also accept a second argument to set the this
keyword for map()
. Or at least, that's what I believe it does.
I decided to test this out with simple arrays:
var numbers = [1, 2, 3];
var letters = ['a', 'b', 'c'];
And a basic function that will be passed as a parameter to map()
:
var effector = function (x) {
console.log(x);
}
What confuses me is why these two function calls result in different outputs:
numbers.map(effector, letters);
numbers.map.call(letters, effector);
I expected both to log the letters to the console, since the this
keyword should reference them (or their objects) respectively.
After further investigation, I experimented with a modified version of the effector function:
var effector = function () {
console.log(this);
}
Again, testing it with:
numbers.map(effector, letters);
numbers.map.call(letters, effector);
Under the assumption of being in "use strict" mode, the first call logs letters
and the second call logs undefined
.
Yet, I still expected both calls to produce the same result.
What am I overlooking?
EDIT:
I came across information about how the .map
method can be polyfilled on MDN, showcasing how the second parameter of callback.call()
is utilized in it.
I presume that ultimately, even callback.call()
should have the same this
reference as in .map
.