多年来一直使用这个网站,但之前从未发布过问题 :-) 来了..
我有一个 javascript 对象,我想在初始化时根据谷歌 API 为其分配一个值。没关系,但谷歌响应不包含对调用它的对象的引用,所以我需要找到一种方法将 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; :-(