函数

时间:2016-05-08 11:10:31

标签: javascript

我正在使用VueJS和GoogleMaps在地图上执行操作。因此我写了这个功能设置:

 methods: {

       // Init GIS
      init: function() {
         initGISMap(this.$els.map);
      },

       updateGIS: function() {
           getAutoCompletePlace(function(place){
               searchMarker.setPosition(place.geometry.location);
               autocompletePlace = place;

               if (place.geometry.viewport) {
                   map.fitBounds(place.geometry.viewport);
               } else {
                   map.setCenter(place.geometry.location);
                   map.setZoom(17);
               }

               self.updateIncidentForm();
           });
       },

      updateIncidentForm: function() {
          console.log("UpdateIncidentForm");
          getAddressComponents(function(components) {
              this.autoCompleteAddress = components;
              this.setIncidentAddressFields(components);
          });
      },
(...)

我想在updateIncidentForm执行时调用getAutocompletePlace函数。我在控制台中遇到的错误是:

  

bundle.js:11073 Uncaught TypeError:self.updateIncidentForm不是   功能

这很奇怪,因为它是代码中定义的函数?我需要以不同的方式调用函数吗?

1 个答案:

答案 0 :(得分:3)

您在回调函数中调用self.updateIncidentForm(),但实际上并未在任何地方定义变量self

据推测,你意味着写下类似的内容:

updateGIS: function() {
    var self = this;                       // <--- you forgot this line!
    getAutoCompletePlace(function(place){
        // (irrelevant code omitted)

        self.updateIncidentForm();
    });
},

var self = this将对您调用updateGIS()方法的对象的引用保存到本地变量self中,以便您可以在传递给的匿名回调函数中使用它getAutoCompletePlace()(其中this的值会有所不同)。

BTW,在现代(ES5.1 +)JavaScript中,实现相同结果的另一种方法是使用bind()来修复回调中this的值,如下所示:

updateGIS: function() {
    getAutoCompletePlace(function(place){
        // (irrelevant code omitted)

        this.updateIncidentForm();
    }.bind(this));
},

回调函数定义locks the value of this末尾的.bind(this)回调到外部updateGIS()函数中的值。