Reputation: 4093
I'm learning about the call()-method in Javascript and trying to understand this ex. Now my question are:
Thanks for yr time!
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); } }).call(animals[i], i); // I cant understand this anonymus func ? :( }
Upvotes: 1
Views: 92
Reputation: 9619
Try adding this code to the end of your example:
animals[0].print();
The anonymous function is invoked using call
which is used to set the this
context within the body of the function. So when the anonymous function uses this
, it is actually getting a referency to the current animal passed in from outside.
The function augments the this
object (which is the currnet animal) with a print
method. This alone will not display anything in the console. It merely means that the print
method has been added to the animal object. But you can then access this method of the object with the code above.
Unfolding the loop, the code is effectively doing the following:
animals[0].print = function () {
console.log('#' + 0 + ' ' + this.species + ': ' + this.name);
}
animals[1].print = function () {
console.log('#' + 1 + ' ' + this.species + ': ' + this.name);
}
The key to understanding this example is to realise that without the use of call
, the this
reference in the anonymous function would automatically refer to the global window
object. It would extend the window
object with a print
method, which obviously isn't what we want.
The next step example would be to obtain the same result by adding a print
method to the object prototype. (This may well be the next example in your book)
Upvotes: 1