I am trying to understand the purpose of using call()
. I read this example on what it's used for, and gathered examples from Mozilla, namely:
var animals = [
{ species: 'Lion', name: 'King' },
{ species: 'Whale', name: 'Fail' }
];
for (var i = 0; i < animals.length; i++) {
(function(i) {
this.print = function() {
console.log('#' + i + ' ' + this.species
+ ': ' + this.name);
}
this.print();
}).call(animals[i], i);
}
I know their example is just for demonstration, but I could easily just access the properties of the object directly in the loop as such:
var animals = [
{ species: 'Lion', name: 'King' },
{ species: 'Whale', name: 'Fail' }
];
for (var i = 0; i < animals.length; i++) {
console.log('#' + i + ' ' + animals[i].species + ': ' + animals[i].name);
}
From this I'm left confused. I still don't see the reason when I'd need to pass a different this
context to call().
Also, with that mozilla example, in the .call(animals[i], i);
function, I have two questions:
the
this
here is theanimals
array. I'm guessing you need call here becauseanimals
is otherwise out of scope to the inner anonymous function?what is the purpose of passing in the index
i
as the second argument in.call(animals[i], i);
?
This question is spurred from the following code segment that I was trying to understand. This code is to gather all inner values from certain spans in a document and join them together. Why do I need to execute call
here on map? Is it because the document.querySelectorAll
is otherwise out of context?
console.log([].map.call(document.querySelectorAll("span"),
function(a){
return a.textContent;
}).join(""));