基本语法

(参数1, 参数2..., 参数n) => {函数声明}单一参数 => { 函数声明 }   (参数1, 参数2...) => 单一表达式() => { 函数声明 }

与一般 function 的区别

  • 箭头函数中的 this 指向的是定义时的对象,而不是使用时的对象
// 事件绑定document.body.addEventListener('click', () => {     console.log(this)  // Window Object})document.body.addEventListener('click', function(){   console.log(this)  // body object})// 对象中的方法var a = {   name: 'a',   getname: () => {       console.log(this)   }}a.getname()  // Windowvar a = {    name: 'a',    getname: function(){        console.log(this)    }}a.getname() // {name: "a", getname: ƒ}
  • 通过 call 或 apply 调用
由于 箭头函数没有自己的this指针,通过 call() 或 apply() 方法调用一个函数时,只能传递参数,他们的第一个参数会被忽略
let f = (val) => {    console.log(this);    console.log(val);}let obj = { count: 1};f.call(obj, 'test')输出: Window      test
  • 不可以使用arguments对象,该对象在函数体内不存在。如果要用,可以用 rest 参数代替
let fn = (a, b) => {    console.log(arguments)  // 报错}// rest参数替代let fn = (...rest) => {    console.log(rest);}fn(1, 2);  // [1,2]
  • 不能用箭头函数定义构造函数,箭头函数不存在 prototype;因此也不能通过 new 关键字调用
let FN = () => {}console.log(FN.prototype)  // undefinedlet fn = new FN();   // Uncaught TypeError: A is not a constructor

原文链接:https://arronf2e.github.io/es6-arrow-functions.html