JavaScript 对象 - 对象值在构造后未定义
JavaScript Objects - Object values getting undefined after constructing
>我正在尝试创建一个处理谷歌地图API的对象,如下所示:
function GoogleMap(container, mapOptions) {
this.Container = container;
this.Options = mapOptions;
this.Map = new google.maps.Map(document.getElementById(this.Container), this.Options);
// Direction
this.DirectionService = new google.maps.DirectionsService();
this.DirectionRenderer = new google.maps.DirectionsRenderer();
this.DirectionRenderer.setMap(this.Map);
this.DirectionId = 0;
this.DirectionResponse = new Array();
this.DrawDirectionDriving = drawDirectionDriving;
}
而 drawDirectionDriving 函数是这样的:
function drawDirectionDriving(start, end) {
var request = {
origin: start,
destination: end,
travelMode: google.maps.TravelMode.DRIVING
};
this.DirectionService.route(request,
function (response, status) {
if (status == google.maps.DirectionsStatus.OK) {
this.DirectionRenderer.setDirections(response);
this.DirectionResponse[this.DirectionId] = response;
this.DirectionId++;
}
else {
alert("Error during drawing direction, Google is not responding...");
}
}
);
}
在某个地方,我像这样使用对象:
var myGoogleMap;
function MapInit() {
myGoogleMap = new GoogleMap("divMap", myMapOptions);
myGoogleMap.DrawDirectionDriving("İstanbul", "Ankara");
}
谷歌地图显示在我的浏览器上,构造对象没有问题,但绘制方向驾驶功能出错。
当我在此行上创建一个断点时:"myGoogleMap.DrawDirectionDriving("İstanbul", "Ankara");" "DirectionRenderer"似乎是构造的,但是在这一行之后(在"Draw"方法之后),DirectionRenderer 对象似乎为空(未定义),因此它会像这样发出 en 错误"无法获得 setDirections 属性,它是空
的等等..."你能帮我一把吗?
提前感谢...
this
关键字确实指向 route
回调函数中的其他内容。DirectionRenderer
属性解析为 null
/undefined
,从中获取 setDirections
属性将导致异常。
使用取消引用变量:
function drawDirectionDriving(start, end) {
var request = {
origin: start,
destination: end,
travelMode: google.maps.TravelMode.DRIVING
};
var that = this;
this.DirectionService.route(request,
function (response, status) {
if (status == google.maps.DirectionsStatus.OK) {
that.DirectionRenderer.setDirections(response);
that.DirectionResponse[this.DirectionId] = response;
that.DirectionId++;
// ^^^^ points to the GoogleMap instance
}
else {
alert("Error during drawing direction, Google is not responding...");
}
}
);
}
相关文章:
- 在CoffeeScript文件上运行Jasmine测试时,对象未定义错误
- JavaScript 对象 - 未定义的数字键文字
- 为什么页面方法对象未定义
- JavaScript对象表示嵌套对象未定义
- Javascript类构造的对象未定义
- JQuery TypeError:对象未定义(length=object.length,)
- 用于从许多带有“for”循环的URL中获取HTML信息的X射线使对象未定义
- 如何避免收到一条消息,指出对象未定义
- JavaScript 对象未定义
- JavaScript 对象未定义它是否在几年前工作
- 揭示模块模式:对象未定义
- 对象未定义/HTML使用jQuery输出
- 为什么子 html 对象未定义/空
- 提取 JSON 对象未定义
- 为什么这个带有最简单的构造函数的 javascript 对象未定义
- “对象”未定义日历.js
- 对象未定义到模块中,Nodejs javascript
- javascript对象未定义
- Twilio响应对象未定义,但没有错误
- 为什么"对象未定义”;在这种情况下没有抛出错误