scope of variables in JavaScript callback functions

前端 未结 5 933
野的像风
野的像风 2020-12-01 06:51

I expected the code below to alert \"0\" and \"1\", but it alert \"2\" twice. I don\'t understand the reason. Don\'t know if it is a problem of jQuery. Also, please help me

5条回答
  •  不知归路
    2020-12-01 07:06

    You're sharing the single i variable among all of the callbacks.

    Because Javascript closures capture variables by reference, the callbacks will always use the current value of i. Therefore, when jQuery calls the callbacks after the loop executes, i will always be 2.

    You need to reference i as the parameter to a separate function.

    For example:

    function sendRequest(i) {
        $.get('http://www.google.com/', function() {
            alert(i);
        });
    }
    
    for (var i = 0; i < 2; i++) {
        sendRequest(i);
    }
    

    This way, each callback will have a separate closure with a separate i parameter.

提交回复
热议问题