I'm trying to understand one of the examples on MDN for Function.prototype.call(), "Using call() to invoke an anonymous function":
const animals = [
{ species: 'Lion', name: 'King' },
{ species: 'Whale', name: 'Fail' }
];
for (let i = 0; i < animals.length; i++) {
(function(i) {
this.print = function() {
console.log('#' + i + ' ' + this.species
+ ': ' + this.name);
}
this.print();
}).call(animals[i], i);
}
Is the i at line #7 (function(i) { a repetition/optional?
It seemed to me that }).call(animals[i], i); at line #12 with the second parameter is already passing i, so to make my test, I wanted to remove it
I mean that at line #7, instead of (function(i) { I have tried (function() { and as I was supposing, it gives the same result.
Thank too Jonsharpe I clarified myself the mechanism
Since this was a didactic question , I share the explicitation to students like me
first of all, the code is misleading, so to better understand it, as suggested by Jonsharpe it is better to replace 'i' with 'index'
const animals = [
{ species: 'Lion', name: 'King' },
{ species: 'Whale', name: 'Fail' }
];
for (let i = 0; i < animals.length; i++) {
(function(index) {
this.print = function() {
console.log('#' + index + ' ' + this.species + ': ' + this.name);
}
this.print();
}).call(animals[i], i);
}
how should it be read, with a paraphrase it does mean
.call the function(index) passing it (animals[i], i) as parameters
the first parameter, an object, is then available through this. the second is passed through index
At line #8 is added and defined a method 'print' to the object
At line #11 this new method is run/called this.print();
The process is repeated animals.length times