1. 程式人生 > >javascript及vue中 this全面指南

javascript及vue中 this全面指南

開發環境:javascript

情況一:物件下的函式中

//test.js
var out = {
	function inner(){
		this
	}
}

此時函式中的this表示out物件。


情況二:函式中

//test.js
function inner(){
	this
}

此時函式中的this表示全域性物件window


開發環境:Vue

情況一:vue元件中

new Vue({
  data: {
    a: 1
  },
  created: function () {
    console.log('a is: ' + this.a)
  }
  methods: {
	plus: function () {
      this.a++
    }
  }
})

vue元件或者例項中,不管是生命週期鉤子函式created還是自定義函式plus,他們中的this都是指當前vue例項。


情況二:回撥函式中

//test.vue
methods: {
     searchLocations: function() {
         var address = this.search
         var geocoder = new window.google.maps.Geocoder()
         geocoder.geocode({
             address: address
         }, function(results, status) {
             if (status === window.google.maps.GeocoderStatus.OK) {
                 this.buscarLojas(results[0].geometry.location)
             }
         })
     },
     buscarLojas: function(center) {
         console.log(center)
     }
 }

此時回撥函式function(results, status)會重新將this指向匿名物件(類比java的匿名類),所以其中的this指代父級元件,執行this.buscarLojas會報錯找不到函式。


情況三:箭頭函式中

//test.vue
methods: {
    searchLocations: function () {
      var address = this.search
      var geocoder = new window.google.maps.Geocoder()
      geocoder.geocode({address: address}, (results, status) => {
        if (status === window.google.maps.GeocoderStatus.OK) {
          this.buscarLojas(results[0].geometry.location)
        } else {
          alert(address + ' not found')
        }
      })
    },
    buscarLojas: function (center) {
      console.log(center)
    }
}

箭頭函式被繫結到父級上下文,因此其中的this會指向父級元件,針對情況三種的問題,將回調函式中的function改成箭頭函式,會將this從匿名物件重新指向外部的vue元件。

參考:
https://stackoverflow.com/questions/51289458/vuejs-this-method-is-not-a-function-how-to-call-a-method-inside-another-method
https://stackoverflow.com/questions/43965714/method-is-not-a-function-in-watcher-callback-vuejs
https://cn.vuejs.org/v2/guide/instance.html?
https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Operators/this