$.Comment = function() {
this.alertme = “Alert!”;
}
$.Comment.prototype.send = function() {
var self = this;
$.post(
self.url,
{
'somedata' : self.somedata
},
function(data) { //using anonymous function to call object's method
self.callback(data);
}
);
}
$.Comment.prototype.callback = function(data) {
alert(this.alertme);
}
This code works great when I’m calling $.Comment.send(), but this code won’t work…
$.Comment.prototype.send = function() {
var self = this;
$.post(
self.url,
{
'somedata' : self.somedata
},
self.callback //using direct access to method
);
}
Please, could you explain me why?
Thank you
The second time, self.callback passes the reference to the function $.Comment.prototype.callback. As with all Javascript functions, this doesn’t carry a binding to the same “this” object (the same reason why you are storing
thisand usingselfabove, but you are using it overzealously).Basically, if a function is used within a different context,
thisno longer refers to the same thing. The first instance above, you storethisasself, and then invokeself.callback(). This invokescallbackwithselfas itsthisobject. The second instance simply passescallbackthe function (without context) to be called. When it is called then,thisis lost.