了解JavaScript闭包-冻结变量传递给回调 [英] Understanding JavaScript Closures - Freeze variable passed to callback

查看:41
本文介绍了了解JavaScript闭包-冻结变量传递给回调的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我还没有对JavaScript闭包的基本了解;

I do not yet have a basic understanding of JavaScript closures;

我有一个关于特定情况的问题,这也许也是基本且常见的例子:

I have a question regarding a specific situation that perhaps is also basic and common example:

在3秒内从1计数到3

在此处查看JSFiddle: http://jsfiddle.net/nAh8x/

See JSFiddle here: http://jsfiddle.net/nAh8x/

代码:

var i,
    t;

t = 0;

// Case A

for( i=1; i<=3; i++ ) {
    setTimeout( function() { log(i); }, t );
    t += 1000;
}

// Case B

for( i=1; i<=3; i++ ) {
    setTimeout( wrapper(i), t );
    t += 1000;
}

function wrapper(i) {
    return function() { log(i); };
}

// Log utility function

function log(msg) {
    $('#log').append( msg + '<br />' );
}

案例 A 不起作用.

我很清楚为什么:每次调用 setTimeout 中的函数并访问 i 变量时,其值已经达到4.

It's clear to me why: every time the function inside setTimeout is called and accesses the i variable, its value has already reached 4.

案例 B 有效.

调用 wrapper(i)时,它将返回

function() { log(i); };

和上面的返回值(一个函数)是setTimeout内部的内容.setTimeout内的内容与案例 A

and the above return value (a function) is what goes inside setTimeout. What goes inside setTimeout is exactly the same as Case A

但是这次, i 变量已被冻结",并带有调用时的值.

But this time, the i variable have been "frozen" with the value at the time of the call.

为什么使用包装器函数冻结传递的值?

Why using the wrapper function let the passed value to be frozen?

对我来说这还不是很清楚.

That's not completely clear to me.

推荐答案

包装函数具有它自己的 i ,它在本地范围内.

The wrapper function has it's own i that is locally scoped to it.

这将在调用 wrapper 时接收其他 i .

This receives the value of the other i at the time wrapper is called.

如果将其重写为以下内容,则可能会更清楚:

It might be clearer if you rewrote it as:

function wrapper(notI) {
    return function() { log(notI); };
}

这篇关于了解JavaScript闭包-冻结变量传递给回调的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆