所以我有一个像这样定义的对象(简化):
mapRoute : {
isInit : false,
latLang : "",
directionsService : null,
directionsRenderer : null,
init : function() {
if(!this.isInit) {
this.directionsService = new google.maps.DirectionsService();
this.directionsRenderer = new google.maps.DirectionsRenderer();
this.directionsRenderer.setPanel(document.getElementById("google_route_results"));
this.isInit = true;
}
},
planRoute : function() {
var from;
var to;
from = $('#addressFrom').val();
to = this.LatLang;
var directionsRequest = {
origin:from,
destination:to,
travelMode: google.maps.DirectionsTravelMode.DRIVING
};
this.directionsService.route(directionsRequest, this.planRouteCallback);
},
planRouteCallback : function(result,status){
if(status == google.maps.DirectionsStatus.OK) {
this.directionsRenderer.setDirections(result);
this.directionsRenderer.setMap(google_map_object);
} else {
this.handleErrors(status);
}
},
//handleErrors
handleErrors : function(statusCode) {
//do stuff
},
}//end mapRoute
但是,当我的 planRouteCallback 执行时,我收到错误,因为“this”引用的是 DomWindow 对象,而不是我的 mapRoute 对象。为什么会这样?我能做些什么吗?
最佳答案
问题在于该函数不是在 mapRoute
对象的上下文中执行的。例如:
var foo = {bar: 10, fn: function(){ alert(this.bar); }};
foo.fn(); // called within the context of the object foo, so it alerts 10
var noContextFn = foo.fn;
noContextFn(); // uh oh, no context, alerts undefined
当您将回调 mapRoute.planRouteCallback
传递给其他函数时,它们现在拥有对正确函数的引用,但不会在 mapRoute
的上下文中执行该回调>,如上所述。
您可以创建一个匿名函数,并在每次将回调作为参数传递时使用 self=this 模式,尽管您最好一劳永逸地修复函数本身。
您可以绑定(bind)该功能。构建 mapRoute
对象后,您可以运行:
mapRoute.planRouteCallback = mapRoute.planRouteCallback.bind(mapRoute);
(注意,bind()
可能无法在所有浏览器中实现,请参阅 MDC 了解您可以使用的实现)。
关于javascript - 为什么在执行谷歌地图方向服务回调时DomWindow对象是 'this',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5834525/