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

时间:2012-08-06 21:59:12

标签: javascript function object methods

我正在尝试创建一个处理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地图显示在我的浏览器上,构建对象没有问题,但在DrawDirectionDriving函数中出错。

当我在此行创建断点时:“myGoogleMap.DrawDirectionDriving(”İstanbul“,”Ankara“);”似乎构造了“DirectionRenderer”,但在此行之后(在“Draw”方法之后),DirectionRenderer对象似乎为null(未定义),因此它出现错误,因为“无法获取setDirections属性,它是null bla bla ...”

你可以帮我一把吗?

提前致谢...

1 个答案:

答案 0 :(得分:2)

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...");
      }
    }
  );
}