JavaScript ES6 Function 箭头函数

传参

1// 默认参数
2// 使用默认参数时,不能有同名形参
3function fn(name, age = 17) {
4  console.log(`${name},${age}`)
5}
6
7function f(...values) {
8  // [1, 2]
9  console.log(values.length) // 2
10}
11f(1, 2) // 2

箭头函数

  • 与一般函数区别
    • 先声明后使用
    • 不能使用 arguments ,使用 ...rest 剩余运算符解决
    • 不能 new 当做构造函数
  • 简写
    • 只有一个形参时可以省略圆括号
    • 只有一条语句,且把这条语句当做返回值时可以省略大括号
  • this 指向
    • this 指向上一层函数的 this
    • 箭头函数的当前调用者不能使用 call,apply、bind 改变 this 指向
  • 不适用场景
    • 对象中的方法不适用箭头函数
    • DOM 绑定事件不适用箭头函数

箭头函数不适用的场景

  1. 对象中的方法不能用箭头函数;
  2. 给 DOM 绑定事件时不能用箭头函数;
1<head>
2  <meta charset="UTF-8" />
3  <meta http-equiv="X-UA-Compatible" content="IE=edge" />
4  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
5  <title>Document</title>
6  <script>
7    let obj = {
8      usr: '李四',
9      test: () => {
10        console.log(this.usr);
11      },
12      test2() {
13        console.log(this.usr);
14      },
15    };
16
17    obj.test(); //undefined
18    obj.test2();
19  </script>
20</head>
21
22<body>
23  <button>测试</button>
24  <script>
25    let btn = document.getElementsByTagName('button')[0];
26    // btn.addEventListener('click', function() {
27    //     console.log(this);
28    // });
29
30    btn.addEventListener('click', () => {
31      console.log(this);
32    });
33  </script>
34</body>