JQuery:在回调中引用外部作用域

Som*_*ica 6 javascript jquery callback

我有OO Javascript和jQuery回调的问题.如果你看下面的样本,它应该解释一切.

如何在这个functception中深入调用functionToCall().

function outerClass() {
    this.functionToCall = function() {
        //do something
    }

    this.someOtherFunction = function() {

    this.aCoupleOfVariables1 = 2;
    this.aCoupleOfVariables2 = "stuff";

    $.ajax({
        success: function() {
        //How do I call functionToCall() right here
        //TRIED:
            functionToCall();
            this.functionToCall();
            that.functionToCall();
        }
    }); 
    }
}
Run Code Online (Sandbox Code Playgroud)

Fré*_*idi 14

你可以通过thiscontext选项$.阿贾克斯() :

$.ajax({
    context: this,
    success: function() {
        // Here, 'this' refers to the same object as in the caller.
        this.functionToCall();  
    }
});
Run Code Online (Sandbox Code Playgroud)

  • 噢,我更喜欢这个. (3认同)
  • 只是OP的旁注:无论何时你需要使用`this`而不能使用`context`或任何其他属性(很多情况),http://api.jquery.com/jQuery.代理/ (2认同)

And*_*rew 6

有一个本地参考,

function outerClass() {

    var self = this;

    this.functionToCall = function() {
    //do something
    }

    this.someOtherFunction = function() {

    this.aCoupleOfVariables1 = 2;
    this.aCoupleOfVariables2 = "stuff";

    $.ajax({
        success: function() {
           self.functionToCall();
       }
    }); 
   }
}
Run Code Online (Sandbox Code Playgroud)


Mat*_*all 5

您需要that在外部范围中定义.

function outerClass() {
    var that = this;

    // ...

     $.ajax({
        success: function() {
            that.functionToCall();
        }
    }); 
}
Run Code Online (Sandbox Code Playgroud)