このサイトを何年も使用していますが、以前に質問を投稿したことはありません:-) ここに行きます..
初期化時に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; :-(