7

This is my issue:

var greatapp = {
  start : function(){
    $.AJAX({
      url : 'foo.com',
      success : function(data){
        greatapp.say(data);
      }
    })
  },

  say : function(s){
    console.log(s);
  }
}

What i don't like about this example is the fact that i repeat my self in the success function by defining the object's name instead of just this which obviously won't work because it's in an external function.

How to only have the name greatapp one time in a JS object?

CodeOverload
  • 47,274
  • 54
  • 131
  • 219
  • See http://stackoverflow.com/questions/183702/access-parents-parent-from-javascript-object – Ivan Jan 03 '12 at 02:21

1 Answers1

10

A common JavaScript idiom is to save the value of this into a variable like me or self, and use that in the callback.

This will work since the callback has access to the variables declared in the enclosing scope—in other words the callback will form a closure over self

var greatapp = {
  start : function(){
    var self = this;
    $.AJAX({
      url : 'foo.com',
      success : function(data){
        self.say(data);
      }
    })
  },

  say : function(s){
    console.log(s);
  }
}
Adam Rackis
  • 82,527
  • 56
  • 270
  • 393