地理位置与打字稿

问题描述:

我有下面的代码片段:地理位置与打字稿

pos:number; 

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

     this.pos = position.coords.latitude; 

当我调试我得到了一个未定义的this.pos,并在position.coords.latitude

一些数字,不过,我有以下几点代码片段:

pos:any; 

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

     this.pos = position.coords.latitude; 

然后设置this.pos。 为什么这样的行为?

+1

您确定这种情况发生了吗?类型注释在最终的javascript中不存在,因此它们不会对代码的行为产生任何影响。也许这是一个调试器的错误...如果你做console.log(this.pos);设置this.pos后它是否输出undefined在第一种情况下仍然 –

如果您确定位置已定义并且您正在进入那里,那是因为this已更改。 this上下文可以根据它的调用方式而改变。如果您通过一个事件调用它,那么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类时都会创建一个新函数。这意味着每个实例都有一个这个函数的副本,而不是共享一个公共内存空间。换句话说,内存的成本更高。

希望这可以解决您的问题。

+0

完美!它为我解决了这个问题。 –

+1

这个答案是前一阵子。今天我推荐'geo.getPosition.bind(geo)' –