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

时间:2011-08-09 14:50:33

标签: javascript jquery callback

我遇到了OO Javascript和jQuery回调的问题。 如果您查看下面的示例,它应该解释所有内容。

如何在这个功能上深入调用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();
        }
    }); 
    }
}

5 个答案:

答案 0 :(得分:14)

您可以将this作为context选项传递给$.ajax()

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

答案 1 :(得分: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();
       }
    }); 
   }
}

答案 2 :(得分:5)

您需要在外部范围内定义that

function outerClass() {
    var that = this;

    // ...

     $.ajax({
        success: function() {
            that.functionToCall();
        }
    }); 
}

答案 3 :(得分:4)

您需要存储来自父作用域的this value的引用:

var parentScope = this;

然后通过该对象访问functionToCall

parentScope.functionToCall();

示例:

function outerClass() {
    var parentScope = this;

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

    // ...

    $.ajax({
       success: function() {
           parentScope.functionToCall();
       }
    });
}

另一种实现方法是使用Es5的.bind()在内部函数中设置this的值(-context)

$.ajax({
    success: function() {
        // Here, 'this' refers to the same object as in the caller.
        this.functionToCall();  
    }.bind(this)
});

答案 4 :(得分:2)

在局部变量中维护函数的范围并使用它,或者您也可以使用jquery proxy来指定上下文。

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

    this.someOtherFunction = function() {

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


    $.ajax({
        success: $.proxy(function() {
            this.functionToCall();
        }, this)
    }); 
    }
}