从内部对象访问父对象

时间:2013-02-20 00:19:37

标签: javascript object prototypejs

我想知道是否有一种优雅的方式来执行以下代码,而不必首先调用父对象“that”。如果我尝试在ajax请求中使用“this”,它显然会引用Ajax对象。

至少我认为这意味着什么。

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();

2 个答案:

答案 0 :(得分:2)

嗯.. that无法在getData内部访问,因为它与initialize的范围不同。重命名this非常常见,因此它可以在内部范围上下文中使用,并且您最终可能想要使用this上下文中应该包含的任何onSuccess,但是你问:

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

行动中:http://jsfiddle.net/ExplosionPIlls/hY3Ca/

答案 1 :(得分:0)

使用bind()

...
onSuccess: function(response) {
   this.workData(response.responseText);
}.bind(this)
...