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
?
You need to pass in the iterator variable so your anonymous function can store that in its own activation object / lexical environment record ( = in its very own context object ).
Furthermore, you need this anonymous function to wrap all access points:
objects[ 'function' + i ] = function( i ) {
var text = function() { return "I am object " + i; };
return text;
}( i );
You need to build a closure, closing over that particular i
variable and returning the function that is untied from i
:
for (var i = 0; i < 10; i++) {
objects['function'+i] = ( function (num) {
return function() {
var text = "I am object " + num;
return text;
};
} )( i ); // <== put the variable into the self-invoking function
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With