<html>
<head>
<script>
function zou() {
var animals = [ {
species : 'Lion',
name : 'King'
}, {
species : 'Whale',
name : 'Fail'
} ];
for ( var i = 0; i < animals.length; i++) {
(function(i) {
this.print = function() {
alert('#' + i + ' ' + this.species + ': ' + this.name);
}
this.print();
}).call(animals[i], i);
}
}
</script>
<title>test</title>
<body>
<a href="javascript:zou()">Let's go!</a>
</body>
</html>
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.