12

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?

2 Answers 2

22

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

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

6 Comments

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?
I had a minor bug. Updated the answer.
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.
Your solution worked for a problem I had with phonegap callback. Thanks.
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?
|
1

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.

Comments

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.