0

我正在尝试从旧的 javascript 编码程序方法转变为更基于对象的方法。我尝试迁移的代码之一是我的位置跟踪器,如下所示:

var gps = new geolocation();

function geolocation() {
  this.watchID;
  this.position;

  this.success = function(p) {
    this.position = p;
  };

  this.failure = function(error) {
    var errmsg;

    // convert the error code to a readable message
    switch(error.code)
    {
        case error.PERMISSION_DENIED:
          errmsg="App doesn't have permission to access your location.";
          break;
        case error.POSITION_UNAVAILABLE:
          errmsg="Your location information is unavailable to App.";
          break;    
        case error.TIMEOUT:
          errmsg="App's request to get your location timed out.";        
          break;
        case error.UNKNOWN_ERROR:
          errmsg="An unknown GPS error occurred.";
          break;
    }
    console.log(errmsg);
  };

  this.watchPosition = function() {
    if(!this.watchID)
    {
      this.watchID = navigator.geolocation.watchPosition(this.success, this.failure, { maximumAge: 1000, timeout: 15000, enableHighAccuracy: true });
    }
  };

  this.getPosition = function() {
    return(this.position);
  };

  this.clearWatch = function() {
    if(this.watchID)
    {
      // turn off the watch
      navigator.geolocation.clearWatch(this.watchID);
      this.watchID = null;
      console.log("GPS WatchID was cleared.", "GPS Status");
    }
  };
};

我可以访问此对象中的所有方法。当我开始 gps.watchPosition(); this.watchID 被设置。但是,当我使用:

var p = gps.getPosition(); 

我将p设为“未定义”,并通过调试器运行显示this.position也未定义。

如果我将这段代码恢复到它的程序状态,它就可以正常工作。显然,我错过了一些东西,但我就是不知道是什么。

(注意:我在发布之前对这段代码做了一些最小化)

4

1 回答 1

0

答案在于“this”——因为显然跟上“this”对于 javascript 工程师来说有点太复杂了,所以在你的对象内部你必须复制“this”,然后使用该副本来引用你的项目目的。

function geolocation() {
  var self = this;
  this.watchID;
  this.position;

  this.success = function(p) {
    self.position = p;
  };
于 2017-11-17T20:56:24.053 回答