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