🎯 学习目标

  • 理解箭头函数的 this 绑定机制
  • 掌握 TypeScript 中的 this 类型
  • 学会使用 this 参数进行类型检查
  • 了解不同场景下的 this 指向

📝 箭头函数特性

// 箭头函数:this 继承自外层作用域 const obj = { name: 'Alice', // 普通函数:this 动态绑定 regularMethod: function() { console.log(this.name); // 'Alice' setTimeout(function() { console.log(this.name); // undefined(严格模式) }, 100); }, // 箭头函数:this 词法绑定 arrowMethod: function() { console.log(this.name); // 'Alice' setTimeout(() => { console.log(this.name); // 'Alice' }, 100); } }; obj.regularMethod(); obj.arrowMethod();
💡
箭头函数 this

箭头函数没有自己的 this,它会捕获定义时外层作用域的 this 值,不会随调用方式改变。

🔧 this 参数类型

// 使用 this 参数指定类型 interface UIElement { addClickListener(onclick: (this: void, e: Event) => void): void; } class Handler { info: string = 'clicked'; // 错误:this 类型不匹配 // onClick(this: Handler, e: Event) { // console.log(this.info); // } // 正确:使用箭头函数 onClick = (e: Event) => { console.log(this.info); }; } // 显式 this 参数 function greet(this: { name: string }) { console.log(`Hello, ${this.name}`); } greet.call({ name: 'Alice' }); // OK greet(); // Error: 必须通过 call/apply/bind 调用

💻 类方法中的 this

class Counter { count = 0; // 方法 1:箭头函数字段(推荐) increment = () => { this.count++; }; // 方法 2:普通方法 + bind decrement() { this.count--; } constructor() { this.decrement = this.decrement.bind(this); } } const counter = new Counter(); const inc = counter.increment; inc(); // OK: count = 1 const dec = counter.decrement; dec(); // OK: count = 0

📝 本节小结

  • • 箭头函数 this 词法绑定
  • • 使用 this 参数进行类型检查
  • • 类方法推荐使用箭头函数字段
  • • 或在构造函数中 bind this