【面试点】:vue中关于this的详解

<template>
  <div class="home">
    1.window的匿名函数 如settimeout(没有箭头)指向是window;函数里面调用要用that变量接一下,才能拿到vue实例,不然指向window
    2.js函数 如foreach ,filter(没有箭头)没有指向,所有函数里面调用,直接指向vue,不用做变量替换
    3.箭头函数,没有具体的this指向,在它内部使用,由宿主对象决定
      3.1匿名函数使用箭头函数写,指向方法的被调用者(vue中是vue)window
      3.2 js函数使用箭头写法,
      3.3 getValue:()=>{console.log(this)}直接使用this,显示未定义
      4 说明:普通函数,都是有this指向的,因为都是window下的函数,所以指向window
  </div>
</template>

<script>

export default {
  data(){
      return {
      showEdit:false
      }
  },
  created() {
    this.getValue1();
    this.getValue2();
    this.getValue22();
    this.getValue3();
    this.getValue33();
    this.getValue4();
    this.getValue5();

    
  },
  methods: {
    getValue1(){
      let that = this;
      setTimeout(function(){
        console.log(this);//window
        console.log(that);//vue
      },1000);
    },
    getValue2(){
      let that = this;
      setTimeout(()=>{
        console.log(this);//vue
        console.log(that);//vue
      },1000);
    },
    getValue22(){
      setTimeout(()=>{
        console.log(this);//vue
      },1000);
    },
    getValue3(){
      [1,2,3,4].forEach((element)=>{
        console.log(element,this);//vue
      })
    },
    getValue33(){
      let that = this;
      [1,2,3,4].forEach(function(element){
        console.log(this,element);//undefined
        console.log(that,element);//vue
      },1000);
    },
    getValue4(){
      let that = this;
      let arr1 = [1,2,3,4];
      let arr2 = [1,2,3,4];
      arr1.filter(function(element){
        console.log(this,element);//undefined
        console.log(that,element);//vue
        return element>2
      })
      arr2.filter((element)=>{
        console.log(this,element);//vue
        console.log(that,element);//vue
        return element>2
      })
    },
    getValue5:()=>{
        console.log(this);//未定义
    }
  },
}
</script>
<style scoped>
  .van-contact-list__add{
    z-index: 0;
  }
  .van-popup{
    height: 100%;
  }
</style>

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

前端小云儿

你的鼓励将是我创作的最大动力

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

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

打赏作者

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

抵扣说明:

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

余额充值