I’m learning about the call()-method in Javascript and trying to understand this ex.
Now my question are:
- Why I can’t see anything in the console(browser); the console.log()-method; is not
working? - How is this anonymus-func working?
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 ? :( }
Try adding this code to the end of your example:
The anonymous function is invoked using
callwhich is used to set thethiscontext within the body of the function. So when the anonymous function usesthis, it is actually getting a referency to the current animal passed in from outside.The function augments the
thisobject (which is the currnet animal) with aprintmethod. This alone will not display anything in the console. It merely means that theprintmethod 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:
The key to understanding this example is to realise that without the use of
call, thethisreference in the anonymous function would automatically refer to the globalwindowobject. It would extend thewindowobject with aprintmethod, which obviously isn’t what we want.The next step example would be to obtain the same result by adding a
printmethod to the object prototype. (This may well be the next example in your book)