If we have the following class (a simplified example):
function MyClass() {
this.greeting = "Where is the ice cream?";
}
MyClass.prototype.talk = function() {
console.log(this.manners(this.greeting));
}
MyClass.prototype.manners = function(phrase) {
return "I beg your pardon. " + phrase;
}
And then we attempt to send it through ajax as follows:
var c = new MyClass();
$.ajax({
data : c,
url : "ajax.php",
dataType : "json",
type : "post"
});
I get an exception from MyClass.prototype.talk, saying that "this.manners is not a function". The reason I get this exception is that, for some reason, the ajax call is forcing all of the methods on MyClass to be called, with a this of Window (rather than an instance of MyClass).
Accordingly, I have a couple of questions:
- Why does the ajax call force every method of the class to be called with Window for
this? - Is it not appropriate to call
mannersfromtalkin the way that I am? Should I be settingthismyself? (not sure how that's possible in this context)
In general, I am still quite ignorant about how and when to use apply and call, so this whole topic is very confusing to me. Whenever I've gotten in trouble in the past with such issues (e.g., in event-handling), I've resorted to the var that = this; work-around, but I think it's time to understand the topic more in-depth. Besides, that fix doesn't work here anyway.