箭头函数最大优势是this绑定不可变、语法无歧义、语义更确定,因其无自身this而继承外层词法作用域的this值,从而避免回调中this指向混乱。
箭头函数最大的优势不是“写得短”,而是 this 绑定不可变、语法无歧义、语义更确定——它把“意外行为”从回调里直接砍掉了。
this 指向混乱?普通函数的 this 是调用时才决定的(动态绑定),而箭头函数压根没有自己的 this,它直接继承外层词法作用域的 this 值(静态绑定)。
setTimeout(function() { this.doSomething(); }, 100) 中的 this 指向 window 或 undefined(严格模式),导致方法调用失败setTimeout(() => this.doSomething(), 100) —— this 就是定义时所在对象的实例map/filter 中需访问组件状态的逻辑箭头函数不是万能替代品;它主动放弃了一些能力,换来的是确定性。以下场景禁用箭头函数:
new 调用会报错:const Person = (name) => { this.name = name; }; new Person('张三'); → TypeError: Person is not a constructor
this 指向全局:const obj = { name: 'Alice', say: () => console.log(t
his.name) }; obj.say(); // undefined(不是 'Alice')arguments 对象时(虽然应优先用剩余参数 ...args),箭头函数不提供 arguments,直接访问会报 ReferenceError
prototype 或想被继承时:箭头函数的 prototype 是 undefined,无法作为构造器或被 class 扩展别只图省字符,要盯住三个关键点:参数括号、返回值、对象字面量。
(),不能省略 —— const tick = () => console.log('tick')
e、item)—— arr.map((x) => x * 2) 比 arr.map(x => x * 2) 更易读{} 会被解析为函数体 —— users.map(u => ({ id: u.id, name: u.name }))
{} 和显式 return —— data.filter((x) => { return x && x.active; })
最常被忽略的一点:箭头函数的“简洁”是设计出来的约束,不是语法糖。你放弃的每个特性(this、arguments、prototype),都是为了换回一个不会在回调里突然失联的执行上下文。