JSFiddle - React, Tailwind, and code Playground

by lasha

JavaScript

var animals = [
  {species: 'Lion', name: 'King'},
  {species: 'Whale', name: 'Fail'}
];

for (var i = 0; i < animals.length; i++) {
  (function (i) { 
    animals[i].print = function () { 
      console.log('#' + i  + ' ' + this.species + ': ' + this.name); 
      // below line writes out data using array[value] instead of this
      document.write('#' + i  + ' ' + animals[i].species + ': ' + animals[i].name + '<br />'); 
    } 
  }).call(animals[i], i);
}

for(var i = 0; i < animals.length; i++) {
    animals[i].print();
}
//animals[0].print();