箭头函数

本文介绍了ES6中的箭头函数,包括其基本使用、参数和返回值的处理,以及箭头函数中this的特殊指向。通过示例代码展示了不同参数数量和代码块形式的箭头函数写法,并通过setTimeout函数演示了箭头函数中this的层层查找特性。
摘要由CSDN通过智能技术生成

初识箭头函数

箭头函数也是一种定义函数的方式,ES6中的函数

1.1 箭头函数的基本使用

定义函数的几种方法以及箭头函数的使用

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>
  <script>
    // 1.function定义函数
    const app = function() {

    }
    // 2.对象字面量定义
    const obj = {
      // aaa:function() {

      // },
      aaa() {
        
      }
    }
    // 3.ES6方式
    // const ccc = (参数列表) => {

    // }
    // 没有参数,最简单箭头函数
    const ccc = () => {

    }
  </script>
</body>
</html>

1.2 箭头函数的参数和返回值

参数问题

两个参数

const a1 = (num1, num2) => {
      return num1 + num2
    }

一个参数,括号可以省略

const a2 = num => {
      return num * num
    }

代码数量问题

一行代码

const a4 = (num1, num2) => num1 + num2

多行代码
括号不能省略

const a3 = () => {
      console.log('一行');
      console.log('两行');
    }

1.3 箭头函数中this的指向

箭头函数的this一层一层向外找
代码测试

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

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

    //   setTimeout(() => {    // window
    //     console.log(this);
    //   }, 1000)
    const obj = {
      aaa() {
        setTimeout(function () {
          setTimeout(function () {
            console.log(this);
          })
          // 箭头作用域中的this指向的是最近作用域中的this
          setTimeout(() => {
            console.log(this);
          })
        })
        // 箭头作用域中的this指向的是最近作用域中的this
        setTimeout(() => {
          setTimeout(function () {
            console.log(this);
          })
          // 箭头作用域中的this指向的是最近作用域中的this
          setTimeout(() => {
            console.log(this);
          })
        })
      },
    }
    obj.aaa()

  </script>
</body>

</html>

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值