简体   繁体   English

Javascript - 帮助理解变量行为

[英]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. 在这两个示例中,变量i被指定为0到9.在第一个示例中,在调用超时函数时, i已经被赋值为9.我不知道超时时i的值组。

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). 在第二个选项中,我们可以通过将其传递到新的上下文来保持i的值(如果这个术语不正确,请纠正我)。

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? 第二个例子给了我期望的值, 0 - 所以就垃圾收集而言,这是如何工作的? At what point will the GC delete this value? GC会在什么时候删除此值? 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; ...) . 在第一个例子中, callback是函数function(){alert('...' + i);} ,其中i是定义callback的范围中的变量,即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. 即使在i0setTimeout(callback, 2000) ,在2000ms之后,这是足够的时间来运行整个for循环, i将变为10,并且当callback时, The first test returns: 10将显示The first test returns: 10

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; ...) . 但是,在进行闭包的第二个示例中, callback本身仍然是function(){alert('...' + i);} ,但由于匿名函数中的参数i其父作用域,因此icallback是参数i在匿名函数中,而不是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 ...) ). 由于JavaScript使用call-by-value,当callback(function(i){...}(i))设置时, i将被“修复”,这使得带有参数i的匿名函数然后立即通过值应用它ifor(var i ...) )。

GC have no role in here. GC在这里没有任何作用。 (Different behavior by GC - except memory usage and timing - means there's a bug in GC.) (GC的不同行为 - 除了内存使用和时间 - 意味着GC中存在错误。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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