0

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

Jompper
  • 1,332
  • 8
  • 15

1 Answers1

1

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.

PSL
  • 120,386
  • 19
  • 245
  • 237
  • So this is the only way ? Just feels pretty stupid that ajaxCallback is a MyClass function, but still unable to access it's variables. – Jompper Dec 28 '13 at 02:30
  • Ok but still I'd need to pass reference to this. Thanks I'll just have to live with that :) – Jompper Dec 28 '13 at 02:38
  • Hey, I managed to make a little simpler solution, cause I have many functions using the same ajax function call. Is there any problem with my approach to problem ? – Jompper Dec 28 '13 at 02:55
  • Don't confuse JavaScript with a strongly-typed language... here, functions are first-class objects too, which means they can go anywhere and anybody can use them. `this` can be a very tricky concept for JavaScript to figure out; try reading [this SO post](http://stackoverflow.com/questions/3127429/javascript-this-keyword) – Hylianpuffball Dec 28 '13 at 02:57
  • @JoniSalmi Yes you could do that as well. But issue could be if you want to use another callback with another bound object or using a call/apply yours will overwrite it. So better you can use it at the caller. – PSL Dec 28 '13 at 02:59