用typescript进行地理定位

用typescript进行地理定位,typescript,geolocation,Typescript,Geolocation,我有以下代码片段: pos:number; getPosition() { navigator.geolocation.getCurrentPosition((position) => { this.pos = position.coords.latitude; pos:any; getPosition() { navigator.geolocation.getCurrentPosition((position) => { t

我有以下代码片段:

pos:number;

getPosition() {
    navigator.geolocation.getCurrentPosition((position) => {

        this.pos = position.coords.latitude;
pos:any;

getPosition() {
    navigator.geolocation.getCurrentPosition((position) => {

        this.pos = position.coords.latitude;
调试时,我在this.pos上未定义,在position.coords.latitude上未定义一些数字

但当我有以下代码片段时:

pos:number;

getPosition() {
    navigator.geolocation.getCurrentPosition((position) => {

        this.pos = position.coords.latitude;
pos:any;

getPosition() {
    navigator.geolocation.getCurrentPosition((position) => {

        this.pos = position.coords.latitude;
然后设置this.pos。
为什么会有这样的行为?

如果你确定位置已经确定,并且你正在进入位置,那么这是因为
这个
已经改变了。
上下文可以根据其调用方式进行更改。如果您是通过事件调用它,那么
this
将在窗口或发起事件的元素的范围内。范例

export class GeoService {
  public pos: any;

  public getPosition() {
    navigator.geoLocation.getCurrentPosition((position) => {
      this.pos = position;
    });
  }
}

let geo = new GeoService();

// When called, `this` will be the window
setTimeout(geo.getPosition, 1000);

// When called, `this` will be the dom element
document.getElementById('myDiv').addEventListener('click', geo.getPosition);
您可以通过使用调用原始对象方法的匿名函数来解决这个问题-

// When called, `this` will be the window
setTimeout(() => { geo.getPosition(); }, 1000);

// When called, `this` will be the dom element
document.getElementById('myDiv').addEventListener('click', () => { geo.getPosition(); });
或者,使用lambda将getPosition设置为GeoService类的属性,以确保其作用域正确

export class GeoService {
  public pos: any;

  public getPosition = () => {
    navigator.geoLocation.getCurrentPosition((position) => {
      this.pos = position;
    });
  }
}
对后者的警告。它可以简化工作并减少冗余代码,但请记住,每次构造GeoService类时,都会创建一个新函数。这意味着每个实例将有一个该函数的副本,而不是共享一个公共内存空间。换句话说,它的内存开销更大


希望这能解决您的问题。

您确定这种行为正在发生吗?类型注释不存在于最终的javascript中,因此它们不会对代码的行为产生任何影响。也许是调试器的错误。。。如果您执行console.log(this.pos);设置this.pos后,它是否会在第一种情况下输出undefined?这是很久以前的答案。今天我推荐
geo.getPosition.bind(geo)