第9章 箭头函数
案例9:箭头函数——改写普通函数并验证调用方式
题目
将普通函数 function(a, b) { return a + b; } 改写为箭头函数,并分别测试直接调用、赋值给变量、作为回调传递三种调用方式,观察 this 绑定差异。
设计思路
箭头函数没有自己的 this,它继承外层作用域的 this。本例先定义普通函数,再改写为箭头函数,通过三类调用方式对比输出,让学习者直观理解箭头函数的词法 this 特性。
核心代码(TypeScript)
// 1. 普通函数
function addNormal(a: number, b: number): number {
return a + b;
}
// 2. 改写为箭头函数
const addArrow = (a: number, b: number): number => a + b;
// 3. 测试三种调用方式
console.log('① 直接调用:', addNormal(3, 5), addArrow(3, 5));
const fn1 = addNormal;
const fn2 = addArrow;
console.log('② 赋值调用:', fn1(1, 2), fn2(1, 2));
const nums = [2, 4, 6];
const mapNormal = nums.map(function(n) { return n * 2; });
const mapArrow = nums.map(n => n * 2);
console.log('③ 回调调用:', mapNormal, mapArrow);
// 4. this 绑定测试
const obj = {
value: 42,
normal: function() {
return function() { return this.value; };
},
arrow: function() {
return () => this.value;
}
};
const normalFn = obj.normal();
const arrowFn = obj.arrow();
console.log('④ this 绑定 → 普通:', normalFn(), '箭头:', arrowFn());
🖥️ 运行结果
① 直接调用: 8 8
② 赋值调用: 3 3
③ 回调调用: [4, 8, 12] [4, 8, 12]
④ this 绑定 → 普通: undefined 箭头: 42
测试建议
在 Node.js 或浏览器控制台运行:tsc arrow.ts && node arrow.js,也可用 ts-node arrow.ts 直接执行。
⚠️ 注意事项
箭头函数不能用作构造函数,不能使用 new 调用;且 arguments 对象不可用(需用剩余参数)。在对象方法中若要访问对象自身,应使用普通函数而不是箭头函数。
🏆 成功要点
核心输出为第④行:普通函数中的 this 指向全局对象(undefined in strict),箭头函数捕获外层 obj 的 this,因此正确输出了 42。