开发者

JQuery: Referencing outer scope within callback

I have an issue with OO Javascript and a jQuery callback. If you look at the sample below it should explain everything.

How do I call functionToCall() deep within this functception.

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

    this.someOtherFunction = function() {

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

    $.ajax({
        success: function() {
        //How do I call functionToCall() r开发者_如何转开发ight here
        //TRIED:
            functionToCall();
            this.functionToCall();
            that.functionToCall();
        }
    }); 
    }
}


You can pass this as the context option to $.ajax():

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


Have a local reference to it,

function outerClass() {

    var self = this;

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

    this.someOtherFunction = function() {

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

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


You need to define that in the outer scope.

function outerClass() {
    var that = this;

    // ...

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


You need to store the reference for the this value from the parent scope:

var parentScope = this;

and then access functionToCall via that object

parentScope.functionToCall();

Example:

function outerClass() {
    var parentScope = this;

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

    // ...

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

Another way to accomplish that would be to use Es5's .bind() to set the value for this within your inner function(-context)

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


Maintain the scope of the function in a local variable and use it or you can also use jquery proxy in which you can specify the context.

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

    this.someOtherFunction = function() {

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


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜