Unable to use "class" methods for callbacks in JavaScript

11,529

Solution 1

Am I trying to force JavaScript into a paradigm which it doesn't belong?

When you're talking about Classes yes.

So what is the right way to do this?

First off, you should learn how what kind of values the this keyword can contain.

  1. Simple function call

    myFunc(); - this will refer to the global object (aka window) [1]

  2. Function call as a property of an object (aka method)

    obj.method(); - this will refer to obj

  3. Function call along wit the new operator

    new MyFunc(); - this will refer to the new instance being created

Now let's see how it applies to your case:

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

If you want to call some_callback method of the current instance you should save the reference to that instance (to a simple variable).

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] please note that in the new version (ES 5 Str.) Case 1 will cause this to be the value undefined

[2] There is yet another case where you use call or apply to invoke a function with a given this

Solution 2

Building on @gblazex's response, I use the following variation for methods that serve as both the origin and target of callbacks:

className.prototype.methodName = function(_callback, ...) {

    var self = (this.hasOwnProperty('instance_name'))?this.instance_name:this;

    if (_callback === true) {

        // code to be executed on callback

    } else {

        // code to set up callback
    
    }

};

on the initial call, "this" refers to the object instance. On the callback, "this" refers to your root document, requiring you to refer to the instance property (instance_name) of the root document.

Share:
11,529
Carson Myers
Author by

Carson Myers

Updated on June 16, 2022

Comments

  • Carson Myers
    Carson Myers almost 2 years

    I'm having a really rough time wrapping my head around prototypes in JavaScript.

    Previously I had trouble calling something like this:

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

    and I was told I could fix it by using:

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

    And this works. I'm now having a different problem, and I thought I could solve it the same way, by just dropping in an 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'm finding that within the body of MyClass.prototype.some_callback the this keyword doesn't refer to the instance of MyClass which the method was called on, but rather what appears to be the jQuery ajax request (it's an object that contains an xhr object and all the parameters of my ajax call, among other things).

    I have tried doing this:

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

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

    I'm not sure how to properly do this. I'm new to JavaScript and the concept of prototypes-that-sometimes-sort-of-behave-like-classes-but-usually-don't is really confusing me.

    So what is the right way to do this? Am I trying to force JavaScript into a paradigm which it doesn't belong?

  • Carson Myers
    Carson Myers over 13 years
    okay, I tried this, but my result is the same: the call to some_callback works, but this inside of some_callback refers to the ajax request object which you highlighted in your first code example. How can I call some_callback in a way that, within the callback, this will refer to the MyClass object which set the callback?
  • gblazex
    gblazex over 13 years
    I had a minor bug. Updated the answer.
  • Carson Myers
    Carson Myers over 13 years
    your updated example works like a charm. I thought I had tried it already and it didn't work... I suppose I made a mistake when I tried that method earlier.
  • Xavier John
    Xavier John about 11 years
    Your solution worked for a problem I had with phonegap callback. Thanks.
  • Sejanus
    Sejanus over 9 years
    Is there a way to register callback method directly, i.e. success: this.some_callback(), without using anonymous function that only serves one purpose, to call another function?
  • gblazex
    gblazex over 9 years
    If you don't need to support old IEs you can use Function.bind like this in the second example: success: self.some_callback.bind(self)