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

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

5 Comments

So this is the only way ? Just feels pretty stupid that ajaxCallback is a MyClass function, but still unable to access it's variables.
Ok but still I'd need to pass reference to this. Thanks I'll just have to live with that :)
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 ?
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
@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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.