箭头函数和普通函数有哪些区别?
核心区别
| 特性 |
普通函数 |
箭头函数 |
this |
动态绑定,由调用方式决定 |
词法 this,继承外层作用域 |
arguments |
有自己的 arguments |
没有,用 ...args 代替 |
new |
可作为构造函数 |
❌ 不能用 new |
prototype |
有 |
❌ 没有 |
super |
❌ |
✅ 可访问外层的 super |
yield |
可用作 generator |
❌ 不能 |
| 严格模式 |
需声明 'use strict' |
内部默认严格模式 |
this 的差异
const obj = {
count: 0,
normalIncrement() {
setInterval(function () {
this.count++
}, 1000)
},
arrowIncrement() {
setInterval(() => {
this.count++
}, 1000)
}
}
不能使用箭头函数的场景
- 对象方法(需要动态 this)
- 原型方法
- 构造函数
- 事件监听器(需要
this 指向 DOM 元素)
- Vue 选项式 API 的 methods
const obj = {
name: 'Tom',
sayHi: () => console.log(this.name)
}
const obj = {
name: 'Tom',
sayHi() { console.log(this.name) }
}
同分类其他题目