Scope of the jquery ajax success callback?

邮差的信 提交于 2019-12-23 04:17:08

问题


if I have

function AjaxRequest(){
    var testvar = 0;
    for(i=0;i<d.length;i++){
        $.ajax({
            success: function(a){
                testvar++;
            }

        });
    }
}

Will testvar increase on success?


回答1:


Yes; the variable is captured by the function's closure.
Closures keep variables alive so that nested functions can still use them later.

Note that the success callbacks only run some time after the rest of your code finishes (AJAX is asynchronous).




回答2:


Yes, it will. It's similar to this:

function() {
   var self = this;
    this.a = function(){
        self.something;
    }
}


来源:https://stackoverflow.com/questions/7326933/scope-of-the-jquery-ajax-success-callback

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!