箭头函数
约 321 字大约 1 分钟
2026-02-26
箭头函数是函数表达式的简洁写法。它最核心的语义不是“更短”,而是“词法 this”。
语法形态
const plus = (a, b) => a + b
const identity = x => x
const createUser = (name, age) => ({ name, age })与普通函数的关键差异
| 对比点 | 普通函数 | 箭头函数 |
|---|---|---|
this | 调用时决定 | 定义时决定(词法绑定) |
arguments | 有 | 没有(可用 rest 代替) |
new 调用 | 可以 | 不可以 |
prototype | 有 | 没有 |
this 的词法绑定
箭头函数中的 this 取自外层作用域,call/apply/bind 无法改写。
const obj = {
count: 0,
start() {
setInterval(() => {
this.count += 1
console.log(this.count)
}, 1000)
}
}适合场景
- 数组处理回调(
map/filter/reduce)。 - 事件回调中需要继承外层
this。 - 函数式管道和组合代码。
不适合场景
- 需要构造函数语义(
new)时。 - 依赖动态
this的对象方法。 - 需要
arguments的旧函数签名场景。
演示:普通函数与箭头函数的 this
<!doctype html>
<html lang="zh-CN">
<body>
<button id="run">运行演示</button>
<pre id="out"></pre>
<script>
const out = document.getElementById('out')
const demo = {
value: 42,
normal: function () {
return this.value
},
arrow: () => this.value
}
document.getElementById('run').addEventListener('click', () => {
const n = demo.normal()
const a = demo.arrow()
out.textContent = [
'normal(): ' + n,
'arrow(): ' + a,
'说明:arrow() 的 this 来自定义位置,不是 demo 对象'
].join('\n')
})
</script>
</body>
</html>