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?
When you’re talking about Classes yes.
First off, you should learn how what kind of values the
thiskeyword can contain.Simple function call
myFunc();–thiswill refer to the global object (akawindow) [1]Function call as a property of an object (aka method)
obj.method();–thiswill refer toobjFunction call along wit the new operator
new MyFunc();–thiswill refer to thenew instancebeing createdNow let’s see how it applies to your case:
If you want to call
some_callbackmethod of the current instance you should save the reference to that instance (to a simple variable).[1] please note that in the new version (ES 5 Str.) Case 1 will cause
thisto be the valueundefined[2] There is yet another case where you use
callorapplyto invoke a function with a giventhis