箭头函数的特征

箭头函数的特征

  1. this是静态的,this 始终指向函数声明时所在作用域下的this值。

  2. 如果是构造函数不能使用构造函数,会抛异常(Person is not a constructor)例如

    let Person = (name, age)=> {
        this.name = name;
        this.age = age
    }
    let p1 = new Person('张三', 20);
    console.log(p1); // Person is not a constructor
    
  3. 不能使用 argument 变量(存储实参),会抛异常(arguments is not defined)。

    let fn = () => {
        console.log(arguments); // arguments is not defined
    }
    
  4. 箭头函数的简写

    1. 省略小括号,当形参有且只有一个参数的时候。

      let add = n => {
          return n + n;
      }
      
    2. 省略花括号,当代码体只有一条语句的时候,此时 return必须省略。

      let pow = n => n*n
      

箭头函数的应用场景

  1. 箭头函数适合于 this无关的回调。(定时器、数组方法回调)
  2. 箭头函数不适合 this有关的回调。(事件回调,对象的方法)
posted @ 2022-02-16 00:00  HuangBingQuan  阅读(75)  评论(0编辑  收藏  举报