简体   繁体   中英

Javascript class ajax callback this that

Javascript

var MyClass = function(){
    var that = this;
    this.bool = false;
}

MyClass.prototype.ajax = function(url, callback){
    $.ajax({
        url: url,
        success: callback
    });
}

MyClass.prototype.ajaxCall = function(){
    this.ajax("ajax.php", this.ajaxCallback);
}

MyClass.prototype.ajaxCallback = function(data){
    that.bool = true;
}

Now the problem is here

that.bool = true;

I made a jsfiddle. http://jsfiddle.net/J3P8t/

Error Uncaught ReferenceError: that is not defined

You could get rid of that and do:

MyClass.prototype.ajaxCall = function(){
    this.ajax("", $.proxy(this.ajaxCallback, this)); //or this.ajaxCallback.bind(this)
}

MyClass.prototype.ajaxCallback = function(data){
    this.bool = true;
}

Or

MyClass.prototype.ajaxCall = function(){
    var self = this;
    this.ajax("your url", function(){
       self.ajaxCallback.apply(self, arguments);
    });
}

MyClass.prototype.ajaxCallback = function(data){
    console.log(data);
    this.bool = true;
}

that is a local variable created in the scope of MyClass constructor function which is not available outside. So accessing an undeclared variable throws an error. using $.proxy or function.prototype.bind you are binding a context to the function reference. SO using it in side the jq ajax call will set the context as that of the MyClass instance instead of jqxhr object.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM