第3章:函数
箭头函数与 this 绑定
1. 箭头函数的基本语法
箭头函数(Arrow Function)是 ES6 引入的一种简洁的函数表达式语法,TypeScript 完全支持并强化了其类型特性。
基本语法:
const add = (a: number, b: number): number => a + b;
特点:
- 省略
function关键字 - 单行时可隐式返回(无
return) - 多行时需显式返回并使用大括号:
const greet = (name: string): string => { return `Hello, ${name}!`; };
2. 箭头函数与普通函数的区别
| 特性 | 箭头函数 | 普通函数 |
|---|---|---|
this 绑定 | 继承外层作用域的 this | 动态绑定(调用时决定) |
| 构造函数 | 不可用作构造函数 | 可以 |
arguments 对象 | 无 | 有 |
prototype 属性 | 无 | 有 |
3. this 绑定的核心规则
箭头函数通过词法作用域(Lexical Scope)绑定 this:
class Counter {
private count = 0;
increment() {
setTimeout(() => {
this.count++; // 正确:箭头函数继承 `increment` 的 `this`
console.log(this.count);
}, 1000);
}
// 若使用普通函数会报错:
brokenIncrement() {
setTimeout(function() {
this.count++; // 错误:`this` 指向全局对象或 undefined(严格模式)
}, 1000);
}
}
4. 使用场景与注意事项
适用场景:
- 需要固定
this的回调函数(如事件监听、定时器) - 简洁的单行函数(如数组方法)
注意事项:
- 避免在需要动态
this的场景使用(如对象方法) - 避免在原型方法中使用箭头函数(会破坏原型链)
5. TypeScript 的类型支持
箭头函数支持完整的类型注解和推断:
// 显式类型注解
const toUpperCase = (str: string): string => str.toUpperCase();
// 类型推断
const numbers = [1, 2, 3];
const doubled = numbers.map(n => n * 2); // 推断为 number[]
6. 练习示例
interface User {
name: string;
age: number;
}
const users: User[] = [
{ name: "Alice", age: 25 },
{ name: "Bob", age: 30 }
];
// 使用箭头函数过滤数据
const adults = users.filter(user => user.age >= 18);
关键总结:箭头函数通过词法作用域解决
this的绑定问题,是 TypeScript 中处理回调函数和保持上下文的重要工具,但需根据场景合理选择箭头函数或普通函数。
