Search code examples
javascriptself-invoking-functionself-executing-function

Using self invoking functions to be variable independent


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?


Solution

  • 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 );