scope of variables in JavaScript callback functions

前端 未结 5 917
野的像风
野的像风 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.

    0 讨论(0)
  • 2020-12-01 07:06

    Alternative to SLaks' answer

    $(function() {
        for (var i=0; i<2; i++) {
            $.get('http://www.google.com/', function(i) {
                return function() { alert(i); }
            }(i));
        }
    });
    
    0 讨论(0)
  • 2020-12-01 07:17

    An alternative solution to this is to take your callback and literally make it a named function.

    Why would I want to do this?
    If a function is doing something where a variable needs to take new scope then it's likely the anonymous function warrants breaking out into a new function. This will also ensure that extra complexity is not introduced to your code by having to copy variables or wrap callbacks. You're code will remain simple and self descriptive.

    Example:

    function getGoogleAndAlertIfSuccess(attemptNumber) {
        $.get('http://www.google.com/', function() {
            alert(attemptNumber);
        });
    }
    
    function testGoogle() {
        for (var i=0; i<2; i++) {
            getGoogleAndAlertIfSuccess(i);
        }
    }
    
    0 讨论(0)
  • 2020-12-01 07:20

    What's occurring here is your AJAX request $.get is completing after the loop has completed. Because of this, i ends up being the final variable it's set to when the iterations complete, being 2. This is just a weird JavaScript gotcha, and has nothing to do with jQuery.

    One thing you can do is queue up these calls asynchronously so that iteration halts until the current AJAX request completes. If you don't want to do that, you can capture the variable i in a function closure in each iteration.

    Something like this:

    for ( var i = 0; i < 2; i++ )
        (function(iter){
            $.get('http://www.google.com/', function(){
                alert( iter );
            });
        })(i); // Capture i
    
    0 讨论(0)
  • 2020-12-01 07:25

    It appears that you've created a closure inside your loop The Mozilla Developers Reference has a good section about this.

    0 讨论(0)
提交回复
热议问题