实现说明
回调场景下的 this 参数标注的核心是类 VoteCounter。
counter、detached、rebinded 定义在模块顶层,中间不经过函数作用域。
使用要点
- 直接运行文件,输出会带上标签,比如
bound:、detached fails with TypeError:、rebinded:——输出的每一行都能指回产生它的那次调用。
常见问题
需要标准库之外的东西吗?
除标准库外不引入任何东西——这个示例没有依赖。 文件的状态由几个模块级绑定持有:counter、detached、rebinded。
核心语句
this.count += by;
代码示例
class VoteCounter {
count = 0;
// this 参数:把方法与实例类型绑死,方法被拆下来调用直接编译报错
increment(this: VoteCounter, by = 1): void {
this.count += by;
}
}
const counter = new VoteCounter();
counter.increment();
counter.increment(4);
console.log('bound:', counter.count);
const detached = counter.increment;
try {
// @ts-expect-error: this 上下文缺失(TS2684)
detached();
} catch (error) {
console.log('detached fails with TypeError:', error instanceof TypeError);
}
const rebinded = counter.increment.bind(counter);
rebinded(2);
console.log('rebinded:', counter.count);