zoukankan      html  css  js  c++  java
  • 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

  • 相关阅读:
    leetcode 2 Add Two Numbers
    leetcode1
    二叉树的最大高度和最大宽度
    插入排序
    eventEmitter学习
    用node.js做一个爬虫
    HTLM5 WebSocket权威指南
    (new Function("return " + json))();
    JS中的this变量的使用介绍
    node.js 模块加载原理
  • 原文地址:https://www.cnblogs.com/zsx-blog/p/12425566.html
Copyright © 2011-2022 走看看