0

我想知道是否有一种优雅的方式来执行以下代码,而不必先调用父对象“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();
4

2 回答 2

2

好吧 ..从内部开始that是不可访问的,因为它的范围与. 重命名非常常见,因此它可以在内部范围上下文中使用,并且您最终可能想要使用上下文中应该存在的任何内容,但是既然您问过:getDatainitializethisthisonSuccess

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

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

于 2013-02-20T00:25:06.323 回答
0

使用bind()

...
onSuccess: function(response) {
   this.workData(response.responseText);
}.bind(this)
...
于 2013-02-20T00:26:53.740 回答