问题
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