特点
- 语法简洁
- 省略function关键字
() => {}- 单行可省略括号
a => a * 2- 单行返回值可以省略
(a, b) => a + b- 返回对象需加括号
() => ({}) - 无独立的this绑定
- 继承
外层作用域的this
- 继承
- 不可作为构造函数
无法用new调用,会报错没有prototype属性,无法用于原型继承或实例化
- 无arguments对象
- 需要用剩余参数替代
访问arguments会引用外层函数的arguments;(...args) => console.log(args) 普通函数 function a () { console.log(arguments) // arguments 类数组对象 }function a() { return () => console.log(arguments) // 拿到外层普通函数的 arguments 类数组对象 } - 不能用做生成器
- 不可使用yield关键字
适用场景
- 需要固定this的上下文
- 如回调函数 / map / filter 等数组方法
- 替代匿名函数
- 简化代码
- 避免this绑定问题
实例对比
// 普通函数
function add(a,b) { return a + b}
const obj = {
count: 1,
increment: function () {
setTimeout(function () {
this.count++ // 错误,这里this 指向window
}, 100)
}
}
// 箭头函数
const add = (a, b) => a + b
const obj = {
count: 1,
increment: function () {
setTimeout(() => {
this.count++ // 2 正确,this指向increment上下文
}, 100)
}
}