Using call to invoke an anonymous function


/ Published in: JavaScript
Save to your folder(s)

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.


Copy this code and paste it in your HTML
  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. }

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

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.