Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unable to use "class" methods for callbacks in JavaScript

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?

like image 202
Carson Myers Avatar asked Oct 25 '10 20:10

Carson Myers


People also ask

Can I call class function from JavaScript?

Also you have created class wrongly, this is not how functions are created in class in JavaScript. Also you can't access class function directly, that's why they are in class. Need to create object of that class and that object will be used to call class function.

What are callback methods in JavaScript?

A JavaScript callback is a function which is to be executed after another function has finished execution. A more formal definition would be - Any function that is passed as an argument to another function so that it can be executed in that other function is called as a callback function.

What can I use instead of callbacks?

Both callbacks and promises help make our code asynchronous. Making callbacks async can cause issues such as callback hell, so to avoid this we can use promises instead, doing this helps us avoid this pitfall while keeping our code async and neat.

Can callbacks have parameters?

Yes. The print( ) function takes another function as a parameter and calls it inside. This is valid in JavaScript and we call it a “callback”. So a function that is passed to another function as a parameter is a callback function.


2 Answers

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

like image 53
25 revs, 4 users 83% Avatar answered Sep 28 '22 07:09

25 revs, 4 users 83%


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.

like image 37
GraceRg Avatar answered Sep 28 '22 08:09

GraceRg