1

このサイトを何年も使用していますが、以前に質問を投稿したことはありません:-) ここに行きます..

初期化時にGoogle APIに基づいて値を割り当てたいJavaScriptオブジェクトがあります。これで問題ありませんが、Google の応答にはそれを呼び出したオブジェクトへの参照が含まれていないため、ID をチェーンに渡す方法を見つける必要があります。

以下の例が理にかなっていることを願っています。基本的に、必要な API 応答には、それを開始したオブジェクトへの参照が含まれていないため、それを呼び出したオブジェクトに関連付ける方法が必要です。

注:これは疑似コードです

    function myClass(param) {
      this.property = param;
      this.distanceFromSomething = 0;
      this.init = function() {
        // this will set this.distanceFromSomething
        var url = 'http:// GOOGLE MAPS API URL BUILT HERE';
        http.get(url, function(res) {
          var body = '';
          res.on('data', function(chunk) {body += chunk;});
          res.on('end', function() {
            var response = JSON.parse(body)
            var distance = response.distance;
            this.distanceFromSomething = distance;
            // 'this' is no longer defined since it's asynchronous... :-(
            // alternative...
            setDistance(ID, distance);
            // and I cannot get the ID of the current object from here either, since it's encapsulated :-(
            // How can this callback function understand which object it relates to?
          }); 
        };
      };
      this.init();
    }

    var entity = new myClass(foo);
    var undefined = entity.distanceFromSomething;  :-(
4

3 に答える 3

0

apply、call、または bind を使用して、関数 (this) のスコープを変更できます (bind は、スコープが変更された別の関数を返します)。

だからあなたの場合はちょうど

function myClass(param) {
  var self = this;
  this.property = param;
  this.distanceFromSomething = 0;
  this.init = function() {
    // this will set this.distanceFromSomething
    var url = 'http:// GOOGLE MAPS API URL BUILT HERE';
    http.get(url, function(res) {
      var body = '';
      res.on('data', function(chunk) {body += chunk;});
      res.on('end', function() {
        var response = JSON.parse(body)
        var distance = response.distance;
        this.distanceFromSomething = distance;
        // 'this' will be from myClass scope
        // alternative...
        setDistance(ID, distance);
        // and I cannot get the ID of the current object from here either, since it's encapsulated :-(
        // How can this callback function understand which object it relates to?
      }.bind(self)); // <--- HERE bind to self
    };
  };
  this.init();
}

または、コールバック内で self を使用することもできます。

EDITそして、初期化されたコードでは、値がフェッチされるまで待つ必要があります:

var entity = new myClass(foo);
(function delay() {
    if (!entity.distanceFromSomething) {
        return setTimeout(delay, 100);
    }
    alert(entity.distanceFromSomething);
});
于 2013-08-14T12:35:14.463 に答える