JavaScript / TypeScript / 系统课时
this 参数
this 参数
本课解决普通函数中的 this 类型不明确或绑定错误的问题。你将使用 TypeScript 的伪参数声明 this 类型,理解它不会进入运行时参数列表,并识别箭头函数不适用该机制的原因。
学习目标
- 为普通函数显式声明
this类型 - 理解
this参数的编译期性质 - 避免函数脱离对象后产生上下文错误
声明 this 参数
this 参数写在参数列表第一位,只参与类型检查,不会生成真实 JavaScript 参数。
ts
type Counter = {
value: number;
increase(this: Counter, step: number): void;
};
const counter: Counter = {
value: 0,
increase(this: Counter, step: number) {
this.value += step;
}
};
counter.increase(3);
console.log(counter.value);预期输出
text
3编译后的函数只接收 step。this: Counter 用于告诉编译器:该函数必须在 Counter 上下文中调用。
检查错误的调用上下文
当方法被单独取出再调用时,运行时 this 可能丢失。显式 this 类型能在编译阶段暴露这一风险。
ts
type Greeter = {
name: string;
greet(this: Greeter): string;
};
const greeter: Greeter = {
name: "TypeScript",
greet(this: Greeter) {
return "Hello, " + this.name;
}
};
console.log(greeter.greet());预期输出
text
Hello, TypeScript不要直接执行 const fn = greeter.greet; fn();。该调用没有满足 Greeter 上下文,开启严格类型检查时会报错。需要保留上下文时,可以使用 bind。
使用 bind 固定 this
bind 会创建一个绑定了上下文的新函数,之后可以安全地单独调用。
ts
type Reporter = {
prefix: string;
report(this: Reporter, message: string): string;
};
const reporter: Reporter = {
prefix: "[APP]",
report(this: Reporter, message) {
return this.prefix + " " + message;
}
};
const boundReport = reporter.report.bind(reporter);
console.log(boundReport("ready"));预期输出
text
[APP] ready箭头函数的限制
箭头函数没有自己的动态 this,它从定义位置捕获外层 this,因此不能声明 this 伪参数。需要对象调用者决定上下文时使用普通函数;需要固定词法上下文时使用箭头函数。
在回调 API 中,也可以声明 this: void,表示回调不应依赖 this。这能阻止传入必须绑定对象才能运行的方法。
按自己的节奏,确认真正理解。