scope of variables in JavaScript callback functions

前端 未结 5 925
野的像风
野的像风 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: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);
        }
    }
    

提交回复
热议问题