0

最初に親オブジェクトを「それ」と呼び出す代わりに、次のコードを実行するエレガントな方法があるかどうか疑問に思っていました。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 に答える