views:

37

answers:

1

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  A: 

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

galambalazs
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?
Carson Myers
I had a minor bug. Updated the answer.
galambalazs
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.
Carson Myers
`this` is a brit tricky, but not hopeless :)
galambalazs