Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using self invoking functions to be variable independent [duplicate]

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?

like image 296
Joncom Avatar asked Jan 15 '23 17:01

Joncom


2 Answers

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 );
like image 174
jAndy Avatar answered Feb 17 '23 11:02

jAndy


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
}
like image 33
Bergi Avatar answered Feb 17 '23 11:02

Bergi