ES6中箭头函数的指向以及声明方式

箭头函数

  • 箭头函数的声明以及使用方法
  1. 多参数声明
    const sum = (num1, num2) => {
      return num1 + num2
    }
  1. 单参数声明
    const power = num => {
      return num * num
    }

  1. 无参数声明
const aaa = ()=>{

}
  1. 函数中的代码数量多
    const test = () => {
      //1. 打印一个hello world
      console.log('Hello world');
      //2. 打印hello Vue.js
      console.log('Hello Vue.js');
    }
  1. 函数中代码数量少,简化写法
    const mul = (num1, num2) => num1 + num2
  • 箭头函数的指向问题

使用场景:一个函数作为另外一个函数的参数时、

结论:箭头函数中的this引用的就是最近作用域中的this

this函数是一层一层查找this,直到有this的定义

<body>
  <script>
    setTimeout(function () {
      console.log(this);
    }, 1000)
    // this指向window

    console.log(this);

    setTimeout(() => {
      console.log(this);
    }, 1000)
    // this指向window,向外找作用域


    const obj = {
      aaa() {

        console.log(this);

        setTimeout(function () {
          console.log(this); //window
        }, 1000)

        setTimeout(() => {
          console.log(this);  //obj对象
        })
      }
    }

    obj.aaa()
  </script>
</body>

Snipaste_2022-05-30_16-58-44

  • 练习

        const bob = {
          aaa() {
            setTimeout(function () {
              setTimeout(function () {
                console.log(this);  //window
              })
    
              console.log(this); //window
    
              setTimeout(() => {
                console.log(this); //window
              })
            })
            setTimeout(() => {
              setTimeout(function () {
                console.log(this);  //window
              })
    
              setTimeout(() => {
                console.log(this);  //obj
              })
            })
          }
        }
    

    Snipaste_2022-05-30_17-14-06

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

抗争的小青年

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

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

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

打赏作者

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

抵扣说明:

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

余额充值