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

JavaScript Objects - Object values getting undefined after constructing

本文关键字:对象 未定义 JavaScript      更新时间:2023-09-26

>我正在尝试创建一个处理谷歌地图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...");
      }
    }
  );
}