Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/436.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何在ajax中将上下文传递到done_Javascript_Ajax_Jquery - Fatal编程技术网

Javascript 如何在ajax中将上下文传递到done

Javascript 如何在ajax中将上下文传递到done,javascript,ajax,jquery,Javascript,Ajax,Jquery,以下是场景: getSomething: function(){ var gotValue = sendAjax(); gotValue.done(function(response){ console.log(response); //How to pass context of object to call getSomethingElse //getSomethingElse(); }); }, getSomethingElse :

以下是场景:

getSomething: function(){
    var gotValue = sendAjax();
    gotValue.done(function(response){
        console.log(response); //How to pass context of object to call getSomethingElse
        //getSomethingElse();
    });
},
getSomethingElse : function(){
}

我想在ajax的done方法中调用getSomethingElse函数

使用
$this=this因为函数中的
不是指对象

getSomething: function()
{
var $this = this;
var gotValue = sendAjax();
gotValue.done(function(response){
   console.log(response);
   $this.getSomethingElse();
});
},
getSomethingElse : function()
{
}
或者你可以使用


使用对当前上下文的引用:

getSomething: function () {
    var self = this;
    sendAjax().done(function (response) {
        self.getSomethingElse(response);
    });
    // or even shorter: sendAjax().done(self.getSomethingElse);
},
getSomethingElse: function () {}
使用方法:

试试这个:

var someHelper = {

    getSomething : function() {

        var gotValue = sendAjax();

        //keep a reference to the obj, normally "this", or "someHelper" 
        var self = this; 

        gotValue.done(function(response) {

            console.log(response); //How to pass context of object to call getSomethingElse
            //getSomethingElse();

            //call getSomethingElse
            self.getSomethingElse();
        });
    },
    getSomethingElse : function() {

    }
}

可以使用apply、call传递对象引用。如果您总是想获取某些引用调用的东西,请使用绑定可能的副本
getSomething: function () {
    sendAjax().done(function (response) {
        this.getSomethingElse(response);
    }.bind(this));
},
getSomethingElse: function () {}
var someHelper = {

    getSomething : function() {

        var gotValue = sendAjax();

        //keep a reference to the obj, normally "this", or "someHelper" 
        var self = this; 

        gotValue.done(function(response) {

            console.log(response); //How to pass context of object to call getSomethingElse
            //getSomethingElse();

            //call getSomethingElse
            self.getSomethingElse();
        });
    },
    getSomethingElse : function() {

    }
}