ES6Arrow-Functions

11次阅读

共计 961 个字符,预计需要花费 3 分钟才能阅读完成。

基本语法

(参数 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()  // Window

var 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)  // undefined

let fn = new FN();   // Uncaught TypeError: A is not a constructor

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

正文完
 0