箭头函数

46 阅读1分钟

一、箭头函数特点
1、相比普通函数,箭头函数有更加简洁的语法

普通函数

    function add(num) {
      return num + 10
    }

箭头函数

    const add = num => num + 10;

2、箭头函数不绑定this,会捕捉其所在上下文的this,作为自己的this。
箭头函数的外层如果有普通函数,那么箭头函数的this就是这个外层的普通函数的this,箭头函数的外层如果没有普通函数,那么箭头函数的this就是全局变量。

       let obj = {
      fn:function(){
          console.log('我是普通函数',this === obj)   // true
          return ()=>{
              console.log('我是箭头函数',this === obj) // true
          }
      }
    }
    console.log(obj.fn()())

.

    let obj = {
fn:()=>{
    console.log(this === window);
}

} console.log(obj.fn()) // true 3、箭头函数不绑定arguments,取而代之用rest参数解决,同时没有super和new.target