【Vue】this代表什么含义


先来个this的翻译帮助下理解
在这里插入图片描述

this 指向并不是在函数定义的时候确定的,而是在调用的时候确定的。换句话说,函数的调用方式(直接调用、方法调用、new调用、bind、call、apply、箭头函数)决定了 this 指向。

1. vue组件中

在Vue所有的生命周期钩子方法(如beforeCreate,created,beforeMount,mounted,beforeUpdate, updated,beforeDestroy以及destroyed)里使用this,this指代调用它的Vue实例,即(new Vue)

new Vue({
  data: {
    a: 1
  },

  created: function () {
    console.log('a is: ' + this.a)
  }

  methods: {
    plus: function () {
      this.a++
    }
  }
});

vue组件或者实例中,不管是生命周期钩子函数created还是自定义函数plus,他们中的this都是指当前vue实例

2. 回调函数

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. 箭头函数

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)
    },
   group1:()=>{
 //ES6的箭头函数写法,箭头函数没有自己的this,它的this事继承来的,指向在定义它时所处的宿主对象,在这里this指向window。
         this.......
   },
}

箭头函数被绑定到父级上下文,因此其中的this会指向父级组件,针对情况三中的问题,将回调函数中的function改成箭头函数,会将this从匿名对象重新指向外部的vue组件

4. 直接调用

函数内部的 this 指向全局对象,在浏览器中全局对象是 window,在 NodeJs 中全局对象是 global。直接调用并不是指在全局作用域下进行调用,在任何作用域下,直接通过 函数名(…) 来对函数进行调用的方式,都称为直接调用。

5. 方法调用

函数中的 this 指向调用该方法的对象。通过对象来调用其方法函数,它是 对象.方法函数(…) 这样的调用形式。

6. new调用

在 es5 中,用 new 调用一个构造函数,会创建一个新对象,而其中的 this 就指向这个新对象。

来源

理解Vue中的this关键字
vuejs中this代表什么含义

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

软泡芙

给爷鞠躬!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值