Search code examples
javascriptobjectprototypejs

Access parent object from inside object


I was wondering if there's an elegant way of doing the following code instead of having to call the parent object "that" first. If I try using "this" from within the ajax request it'll obviously refer to the Ajax object.

At least that's what I think it means.

var ObjectA = Class.create();

ObjectA.prototype = {
  initialize: function() {
  //Workaround I use
  that = this;
  },

getData: function(bounds) {
  //ajax to get some data       
  url = "http://www.data.com/";     

  new Ajax.Request(url, {
    method: 'get',
    onSuccess: function(response) {
    // Handle the response content...
    that.workData(response.responseText);
    //THIS IS MY DOUBT.
    //How do I access the parent object without having to previously calling it "that" first?
    }
  });

},
workData: function(data){
//do something with the data
}

} 

var test = new ObjectA();
test.getData();

Solution

  • Well .. that is not accessible inside of getData to begin with since it's a different scope than initialize. It's very common to rename this so it can be used in inner scope contexts, and you may end up wanting to use whatever this is supposed to be in the onSuccess context anyway, but since you asked:

    onSuccess: function (response) {
        //this is now ObjectA
    }.bind(this);
    

    In action: http://jsfiddle.net/ExplosionPIlls/hY3Ca/