使用打字稿进行地理定位

ada*_*wak 5 geolocation typescript

我有以下代码片段:

pos:number;

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

        this.pos = position.coords.latitude;
Run Code Online (Sandbox Code Playgroud)

当我调试时,我在 this.pos 上没有定义,在 position.coords.latitude 上有一些数字

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

pos:any;

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

        this.pos = position.coords.latitude;
Run Code Online (Sandbox Code Playgroud)

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

mic*_*cah 1

如果您确定位置已定义并且您正在进入该位置,那么这是因为位置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);
Run Code Online (Sandbox Code Playgroud)

您可以通过使用调用原始对象方法的匿名函数来解决这个问题 -

// 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(); });
Run Code Online (Sandbox Code Playgroud)

或者,通过使用 lambda 将 getPosition 设置为 GeoService 类的属性,以确保其范围正确。

export class GeoService {
  public pos: any;

  public getPosition = () => {
    navigator.geolocation.getCurrentPosition((position) => {
      this.pos = position;
    });
  }
}
Run Code Online (Sandbox Code Playgroud)

对后者的警告。它可以使事情变得更简单并减少冗余代码,但请记住,每次构造 GeoService 类时都会创建一个新函数。这意味着每个实例都将拥有该函数的副本,而不是共享公共内存空间。换句话说,它的内存成本更高。

希望这能解决您的问题。