State of Javascript Global Variable binding Inside a function
I am carrying out an AJAX call (with dojo) and I wanted to know what's the best way to have to pass the calling object to the callback function
var that = this;
dojo.xhrGet({
url : 'script.php',
handleAs : "javascript",
load : function(response开发者_运维百科){
/*The callback on success*/
console.log('Ajax Completed Successfully for: ' + that.name);
}
});
My question is whether load
is created at 'compile time', or whether it is evaluated at 'run time'. Basically, if the value of that
changes between when it is created var that = this
and when it is called after AJAX returns and calls load
, will this change be reflected in load
? If so, then what's the best practice for ensuring the AJAX return signal calls the correct object? Do I have to create a specific load function for every object?
Thanks
You can enclose your load inside a closure
:
(function(that){
dojo.xhrGet({
url : 'script.php',
handleAs : "javascript",
load : function(response){
/*The callback on success*/
console.log('Ajax Completed Successfully for: ' + that.name);
}
});
})(this);
The (function(x){ })(x);
part is a self executing function which gives the value of x
or this
as an argument to the self executing function. The value x
or that
remains what it should be.
Depending on what you want to do, you can avoid having to create with the load:
at all by using deferreds:
function get_data(){
return dojo.xhrGet({
url : 'script.php',
handleAs : "javascript",
});
}
function other_function(){
var that = this;
get_data().then(function(response){
console.log("Ajax completed for" + that.name);
});
}
(I don't remember if this also works when the ajax fails - need to test this bit)
精彩评论