2016-05-08 97 views
-1

我正在使用VueJS和GoogleMaps在地圖上執行操作。因此,我寫了這個功能設置:函數內的Javascript函數調用

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 is not a function

這很奇怪,因爲它是代碼中定義的函數?我需要以不同的方式調用函數嗎?

+5

你的'var self'在哪裏? –

回答

3

您在回調函數中調用self.updateIncidentForm(),但實際上並沒有在任何地方定義變量self

想必,你意味着寫類似:

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

     self.updateIncidentForm(); 
    }); 
}, 

var self = this保存到你呼籲到局部變量selfupdateGIS()方法的對象的引用,這樣就可以在裏面使用它的行您傳遞給getAutoCompletePlace()的匿名回叫函數(其中值this將有所不同)。


順便說一句,在現代(ES5.1 +)的JavaScript,另一種方式來達到同樣的效果是使用bind()來修復您的回調中的this值,就像這樣:

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

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

.bind(this)在回調函數結束時定義locks the value of this裏面的回調函數,它具有在外部updateGIS()函數中的值。