gpt4 book ai didi

JavaScript 对象 - 构造后对象值未定义

转载 作者:行者123 更新时间:2023-12-02 19:27:51 25 4
gpt4 key购买 nike

我正在尝试创建一个处理 Google Maps 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");
}

Google map 显示在我的浏览器上,构造对象没有问题,但 DrawDirectionDriving 函数出错。

当我在此行上创建断点时:“myGoogleMap.DrawDirectionDriving(" Istanbul 尔", "安卡拉");"“DirectionRenderer”似乎已构建,但在这一行之后(在“Draw”方法之后),DirectionRenderer 对象似乎为 null(未定义),因此它会出现这样的错误“无法获取 setDirections 属性,它为 null bla bla ...”

你能帮我一下吗?

提前致谢...

最佳答案

this keyword确实指向 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...");
}
}
);
}

关于JavaScript 对象 - 构造后对象值未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11836580/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com