首页 > 其他 > 详细

vue箭头函数和普通函数的this区别

时间:2020-03-06 11:49:17      阅读:239      评论:0      收藏:0      [点我收藏+]
<template>
<p>my test </p>
</template>

<script>
export default {
  name: ‘Test‘,
  data () {
    return {
    }
  },
  mounted () {
    setTimeout(() => {
      console.log(‘箭头函数‘, this)
    }, 500)// 打印结果 vueComponent

    setTimeout(function () {
      console.log(‘匿名函数‘, this)
    }, 500)// 打印结果 Window

    this.printThis()
  },

  methods: {
    printThis (file) {
      console.log(‘普通函数‘, this)// 打印结果 vueComponent
    }
  }
}
</script>

箭头函数和普通函数的this区别如下。

普通函数:调用时被决定。
根据调用我的人(谁调用我,我的this就指向谁),
this对象是在运行时基于函数的执行环境绑定的:在全局函数中,this指向的是window;当函数被作为某个对象的方法调用时,this就等于那个对象

箭头函数:定义时被决定。
根据所在的环境(我在哪个环境中,this就指向谁),函数在定义时,this就继承了定义函数的对象。

匿名函数:匿名函数的执行环境是全局性的。
匿名函数中this指向window

vue箭头函数和普通函数的this区别

原文:https://www.cnblogs.com/zsx-blog/p/12425566.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!