基本语法
(参数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: ƒ}
因为 箭头函数没有本身的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/post/es6-arrow-functionsgit