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

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值