Possible Duplicate:
Javascript closure inside loops - simple practical example
I'm trying to use a self invoking function so that each function in objects
will return a different message.
<script type="text/javascript">
objects = {};
for( var i = 0; i < 10; i++ ) {
objects['function'+i] = function () {
var text = ( function() { return "I am object " + i; } )();
return text;
};
}
for( var j = 0; j < 10; j++ ) {
document.write( objects['function'+j]() + "<br>" );
}
</script>
So far the above results in:
I am object 10
I am object 10
I am object 10
I am object 10
I am object 10
I am object 10
I am object 10
I am object 10
I am object 10
I am object 10
How can I use self invoking-functions to set the message immediately and not be tied to the precarious i
?