Cannot use class methods for callbacks in JavaScript

I have a very difficult time wrapping my head around prototypes in JavaScript.

I used to have to call something like this:

o = new MyClass();
setTimeout(o.method, 500);

and they told me that I can fix this using:

setTimeout(function() { o.method(); }, 500);

And it works. I have a different problem now, and I thought I could solve it the same way, just by dropping the anonymous function. My new problem is this:

MyClass.prototype.open = function() {
    $.ajax({
        /*...*/
        success: this.some_callback,
    });
}

MyClass.prototype.some_callback(data) {
    console.log("received data! " + data);
    this.open();
}

I find that in the body the MyClass.prototype.some_callbackkeyword thisdoes not refer to the instance the MyClassmethod was called on, but rather what looks like a jQuery ajax request (it is an object that contains the xhr object and all the parameters of my ajax call, by the way).

I tried to do this:

$.ajax({
    /* ... */
    success: function() { this.some_callback(); },
});

but I get the error:
Uncaught TypeError: Object #<an Object> has no method 'handle_response'

, . JavaScript, - , , - , - -, , , .

, ? JavaScript , ?

+5
1

JavaScript , ?

yes.

, ?

-, , this.

  • myFunc(); - this (aka window) [1]

  • ( aka)

    obj.method(); - this obj

  • new MyFunc(); - this new instance

, :

MyClass.prototype.open = function() {
    $.ajax({ // <-- an object literal starts here
        //...
        success: this.some_callback,  // <- this will refer to that object
    });      // <- object ends here
}

some_callback , ( ).

MyClass.prototype.open = function() {
    var self = this; // <- save reference to the current instance of MyClass
    $.ajax({ 
        //...
        success: function () {
            self.some_callback();  // <- use the saved reference
        }                          //    to access instance.some_callback
    });                             
}

[1] , (ES 5 Str.) 1 , this undefined

[2] , call apply, this

+12

All Articles