简体   繁体   中英

Javascript - Help understanding variable behaviour

Take the two examples below. In both examples, the variable i is assigned as 0 through 9. In the first example, by the time the timeout function is called, i has already been assigned the value of 9. I do not know the value of i when the timeout was set.

for(var i = 0; i < 10; i++) {
    var callback = function() {
        alert('The first test returns: ' + i);
    };

    if(i === 0) setTimeout(callback, 2000);
}

In the second option, we are able to persist the value of i by passing it into a new context (please correct me if this terminology is incorrect).

for(var i = 0; i < 10; i++) {
    var callback = (function(i) {
        return function() {
            alert('The second test returns: ' + i);
        }
    })(i);

    if(i === 0) setTimeout(callback, 2000);
}

The second example gives me the value I expect, 0 - so how does this work as far as garbage collection goes? At what point will the GC delete this value? At the end of the callback function? Or will there be some sort of memory leak?

In the first example, callback is the function function(){alert('...' + i);} , where i is the variable in the scope where callback is defined, ie i in for(var i = 0; ...) .

Even though setTimeout(callback, 2000) is called when i is 0 , after 2000ms, which is sufficient time to run through whole for loop, i will become 10, and when callback is called, The first test returns: 10 will be shown.

However, in the second example where a closure is made, callback itself is still function(){alert('...' + i);} , but since argument i in an anonymous function shadows its parent scope, i in callback is argument i in the anonymous function, not the i in for(var i = 0; ...) .

Since JavaScript uses call-by-value, that i will be 'fixed' when callback is set by (function(i){...}(i)) , which makes an anonymous function with argument i then apply it immediately by value i (in for(var i ...) ).

GC have no role in here. (Different behavior by GC - except memory usage and timing - means there's a bug in GC.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM