Google Geocoder 和 TypeScript 中的“this”引用

Google Geocoder and 'this' reference in TypeScript

本文关键字:this 引用 中的 Geocoder TypeScript Google      更新时间:2023-09-26

调用地理编码器后,我在尝试获取对主对象的引用时遇到问题。

export class Oferta{
   _self: any;
   geocoder: any;
   contructor (){
      this._self = this;
      this.geocoder = null;
   }
   geolocalizate(){
      var _this = this;
      var address = "Home";
      this.geocoder = new google.maps.Geocoder();
      this.geocoder.geocode({
         'address': address
      }, function(results,status){
          // 'this' here is a reference to 'window'
          // _self and _this are 'undefined' 
      });
   }
}

我无法找到解决此问题的方法

> 只需使用箭头函数=>而不是function 。也不要_this因为打字稿保留了用于词汇范围。完成:

export class Oferta{
   _self: any;
   geocoder: any;
   constructor (){
      this._self = this;
      this.geocoder = null;
   }
   geolocalizate = () => {        // ARROW 
      var address = "Home";
      this.geocoder = new google.maps.Geocoder();
      this.geocoder.geocode({
         'address': address
      }, (results,status) => {   // ARROW 
          // use `this` 
      });
   }
}

更多 : https://www.youtube.com/watch?v=tvocUcbCupA&hd=1

你也拼错了constructor,这就解释了为什么_self错了。