开发者

Scope of the jquery ajax success callback?

开发者 https://www.devze.com 2023-04-03 16:04 出处:网络
if I have function AjaxRequest(){ var testvar = 0; for(i=0;i<d.length;i++){ $.ajax({ success: function(a){

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?


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).


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

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

精彩评论

暂无评论...
验证码 换一张
取 消