0

I have the following code:

var Foo = function(){
    this._temp="uh";
};

Foo.prototype._handler=function(data, textStatus){
    alert(this._temp);
}

Foo.prototype.run=function(){
    $.ajax({
        url: '....', 
        success: this._handler
    });
}

So when I rum it:

new Foo().run();

And ajax query has come back, the handler is processed and I get error that this._temp is undefined. What is the reason and how to fix it using this code template?

1 Answer 1

3
$.ajax({
    url: '....', 
    success: this._handler.bind(this)
});

You need to bind the context of the function.

If you using the debugger (available in the web browser), you will see that this was not referring to your object instance.

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

Comments

Your Answer

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