Javascript 全局变量绑定的状态 在函数内

State of Javascript Global Variable binding Inside a function

本文关键字:函数 状态 全局变量 绑定 Javascript      更新时间:2023-09-26

我正在执行一个 AJAX 调用(使用 dojo(,我想知道将调用对象传递给回调函数的最佳方法是什么

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);
    }
});

我的问题是load是在"编译时"创建的,还是在"运行时"计算的。基本上,如果that的值在创建var that = this和在 AJAX 返回并调用load后调用它之间发生变化,这种变化会反映在load中吗?如果是这样,那么确保 AJAX 返回信号调用正确对象的最佳实践是什么?我是否必须为每个对象创建一个特定的加载函数?

谢谢

您可以将

负载括在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);

(function(x){ })(x);部分是一个自执行函数,它给出xthis的值作为自执行函数的参数。xthat的值保持应有的状态。

根据您要执行的操作,可以通过使用延迟来避免使用load:创建:

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);
    });
}

(我不记得当 ajax 失败时这是否也有效 - 需要测试这一点(