如何在ajax中传递上下文

时间:2013-11-29 07:55:18

标签: 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 : function(){
}

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

3 个答案:

答案 0 :(得分:2)

使用$this=this;,因为函数中的this未引用该对象。

getSomething: function()
{
var $this = this;
var gotValue = sendAjax();
gotValue.done(function(response){
   console.log(response);
   $this.getSomethingElse();
});
},
getSomethingElse : function()
{
}

或者您可以使用$.proxy

gotValue.done($.proxy(function(response){
   console.log(response);
   this.getSomethingElse();
},this));

答案 1 :(得分:0)

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

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

使用bind方法:

getSomething: function () {
    sendAjax().done(function (response) {
        this.getSomethingElse(response);
    }.bind(this));
},
getSomethingElse: function () {}

答案 2 :(得分:0)

试试这个:

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() {

    }
}