views:

22

answers:

1

Hello,

$.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

+1  A: 

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.

Antonio Salazar Cardozo
Thank you for your answer. Sorry for my English, but what do you mean saying "but you are using it overzealously"? Other part of your answer is clear for me, thank you!
Kirzilla
Sorry. Basically you're using `self` where `this` is still valid. this is only invalid when you're passing a function to another function to be invoked there. If you're in the current function, `this` is still valid.
Antonio Salazar Cardozo