JQuery:在回调中引用外部作用域
我有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(); } }); } }
您可以this
作为context
选项传递给$ .ajax() :
$.ajax({ context: this, success: function() { // Here, 'this' refers to the same object as in the caller. this.functionToCall(); } });
有一个本地参考,
function outerClass() { var self = this; this.functionToCall = function() { //do something } this.someOtherFunction = function() { this.aCoupleOfVariables1 = 2; this.aCoupleOfVariables2 = "stuff"; $.ajax({ success: function() { self.functionToCall(); } }); } }
您需要在外部范围中定义that
。
function outerClass() { var that = this; // ... $.ajax({ success: function() { that.functionToCall(); } }); }
您需要从父作用域存储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()
在你的内部函数中设置它的值(-context)
$.ajax({ success: function() { // Here, 'this' refers to the same object as in the caller. this.functionToCall(); }.bind(this) });
在本地变量中维护函数的范围并使用它,或者您也可以使用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) }); } }