Posted By

hellowouter on 03/30/12


Tagged

array function call Anonymous


Versions (?)

Using call to invoke an anonymous function


 / Published in: JavaScript
 

URL: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function/call

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.

  1. var animals = [
  2. {species: 'Lion', name: 'King'},
  3. {species: 'Whale', name: 'Fail'}
  4. ];
  5.  
  6. for (var i = 0; i < animals.length; i++) {
  7. (function (i) {
  8. this.print = function () {
  9. console.log('#' + i + ' ' + this.species + ': ' + this.name);
  10. }
  11. }).call(animals[i], i);
  12. }

Report this snippet  

You need to login to post a comment.