Revision: 56484
Initial Code
Initial URL
Initial Description
Initial Title
Initial Tags
Initial Language
at March 30, 2012 18:53 by hellowouter
Initial Code
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); }
Initial URL
https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function/call
Initial Description
In this purely constructed example, we create anonymous function and use call to invoke it on every object in an array. The main purpose of the anonymous function here is to add a print function to every object, which is able to print the right index of the object in the array. Passing the object as this value was not strictly necessary, but is done for explanatory purpose.
Initial Title
Using call to invoke an anonymous function
Initial Tags
array, function
Initial Language
JavaScript