JAvascriptおよびvueにおけるthisの全面的なガイドライン

9998 ワード

開発環境:javascript
ケース1:オブジェクトの下の関数
//test.js
var out = {
	function inner(){
		this
	}
}

このとき、関数のthisはoutオブジェクトを表します.
ケース2:関数
//test.js
function inner(){
	this
}

このとき関数のthisはグローバルオブジェクトwindowを表します
開発環境:Vue
ケース1:vueコンポーネント
new Vue({
  data: {
    a: 1
  },
  created: function () {
    console.log('a is: ' + this.a)
  }
  methods: {
	plus: function () {
      this.a++
    }
  }
})

vueコンポーネントまたはインスタンスでは、ライフサイクルフック関数createdまたはカスタム関数plusにかかわらず、現在のvueインスタンスを指します.
ケース2:コールバック関数
//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を実行すると関数が見つからないとエラーが表示されます.
ケース3:矢印関数
//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