vue箭头函数、普通函数、匿名函数的this区别


<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就指向谁),Arrow functions bind the parent context。

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


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM