I can get access to object's properties if method is called from anonymous function, but I can't do it if method is called directly. Why?
$.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 wor开发者_高级运维ks 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 this and using self above, but you are using it overzealously).
Basically, if a function is used within a different context, this no longer refers to the same thing. The first instance above, you store this as self, and then invoke self.callback(). This invokes callback with self as its this object. The second instance simply passes callback the function (without context) to be called. When it is called then, this is lost.
加载中,请稍侯......
精彩评论