本文旨在解决TypeScript类方法中this上下文意外变为undefined
或指向错误对象的问题,特别是在方法作为回调或被解构调用时。我们将深入探讨JavaScript/TypeScript中this的工作原理,分析导致上下文丢失的常见场景,并提供两种主要解决方案:使用箭头函数作为类属性以及在构造函数中绑定方法,以确保this始终正确指向类实例。
在JavaScript和TypeScript中,this关键字的行为是一个常见的混淆点,它的值取决于函数被调用的方式,而非函数被定义的位置。当this在类方法中意外地变成undefined或指向全局对象(严格模式下为undefined,非严格模式下为window或global)时,通常意味着方法的调用上下文发生了变化。
考虑以下Configs类,其中包含一些配置数据和操作这些数据的方法:
import { log } from 'console';
// import { ITimeFrameTypes } from '../tbBot/bot.interface'; // 假设这个接口已定义
// 模拟 ITimeFrameTypes 接口
type ITimeFrameTypes = '1m' | '5m' | '15m' | '1h' | '4h' | '1d' | '1M';
export class Configs {
private initMargin = 1;
private initLevrage = [
100, 90, 80, 70, 60, 50, 40, 30, 20, 15, 13, 11, 10, 8, 6, 5, 4, 3,
];
private timeFrames: ITimeFrameTypes[] = [
'1m',
'5m',
'15m',
'1h',
'4h',
'1d',
'1M',
];
checkFrameType(name: ITimeFrameTypes) {
let t: string = name;
if (name == '1M') {
t = '1mo';
}
return t;
}
getMarginInit() {
return this.initMargin;
}
setMarginInit(n: number) {
this.initMargin = n;
}
getLevrages() {
return this.initLevrage.map(x => x);
}
getTimes() {
return this.timeFrames.map(x => x);
}
getTimeName(i: number) {
// 当 this 上下文丢失时,this.initLevrage 会是 undefined
log(typeof this.initLevrage); // 此时可能输出 'undefined'
let t = this.timeFrames[i];
return this.checkFrameType(t);
}
getTimeIndex(name: ITimeFrameTypes) {
let t = this.timeFrames.indexOf(name);
return t;
}
}当getTimeName方法被调用时,如果this.initLevrage变为undefined,并导致TypeError: Cannot read properties of undefined (reading 'initLevrage'),这通常意味着getTimeName方法在被调用时,其this上下文不再指向Configs类的实例。
这种情况常见于以下场景:
const myConfigs = new Configs(); setTimeout(myConfigs.getTimeName, 1000, 0); // this 将丢失
const myConfigs = new Configs();
const { getTimeName } = myConfigs;
getTimeName(0); // this 将丢失在这些情况下,JavaScript的默认绑定规则会导致this指向调用函数的环境,而不是原始的类实例。在严格模式下(ES模块和类内部默认是严格模式),this将是undefined。
为了解决this上下文丢失的问题,我们可以采用两种主要策略来显式地绑定this。
这是解决此类问题的现代且简洁的方法。当一个箭头函数被用作类的属性时,它会词法绑定this。这意味着this的值将是箭头函数定义时所在作用域的this,即类的实例。
修改后的Configs类示例:
import { log } from 'console';
// import { ITimeFrameTypes } from '../tbBot/bot.interface';
type ITimeFrameTypes = '1m' | '5m' | '15m' | '1h' | '4h' | '1d' | '1M';
export class Configs {
private initMargin = 1;
private initLevrage = [
100, 90, 80, 70, 60, 50, 40, 30, 20, 15, 13, 11, 10, 8, 6, 5, 4, 3,
];
private timeFrames: ITimeFrameTypes[] = [
'1m',
'5m',
'15m',
'1h',
'4h',
'1d',
'1M',
];
checkFrameType(name: ITimeFrameTypes) {
let t: string = name;
if (name == '1M') {
t = '1mo';
}
return t;
}
getMarginInit = () => { // 修改为箭头函数
return this.initMargin;
}
setMarginInit = (n: number) => { // 修改为箭头函数
this.initMargin = n;
}
getLevrages = () => { // 修改为箭头函数
return this.initLevrage.map(x => x);
}
getTimes = () => { // 修改为箭头函数
return this.timeFrames.map(x => x);
}
// 关键修改:将 getTimeName 方法定义为箭头函数作为类属性
getTimeName = (i: number) => {
// 此时 this 始终指向 Configs 实例
log(typeof this.initLevrage); // 将正确输出 'object'
let t = this.timeFrames[i];
return this.checkFrameType(t);
}
getTimeIndex = (name: ITimeFrameTypes) => { // 修改为箭头函数
let t = this.timeFrames.indexOf(name);
return t;
}
}通过将getTimeName(以及其他可能需要this绑定保证的方法)定义为箭头函数,即使它作为回调函数被传递或被解构调用,this也将始终正确地指向Configs类的实例。
优点:
缺点:
另一种确保this正确绑定的方法是在类的构造函数中使用bind()方法显式地绑定方法的this上下文。
import { log } from 'console';
// import { ITimeFrameTypes } from '../tbBot/bot.interface';
type ITimeFrameTypes = '1m' | '5m' | '15m' | '1h' | '4h' | '1d' | '1M';
export class Configs {
private initMargin = 1;
private initLevrage = [
100, 90, 80, 70, 60, 50, 40, 30, 20, 15, 13, 11, 10, 8, 6, 5, 4, 3,
];
private timeFrames: ITimeFrameTypes[] = [
'1m',
'5m',
'15m',
'1h',
'4h',
'1d',
'1M',
];
constructor() {
// 在构造函数中绑定方法
this.getTimeName = this.getTimeName.bind(this);
// 如果其他方法也需要确保this绑定,也需要在这里绑定
this.getMarginInit = this.getMarginInit.bind(this);
// ... 其他方法
}
checkFrameType(name: ITimeFrameTypes) {
let t: string = name;
if (name == '1M') {
t = '1mo';
}
return t;
}
getMarginInit() {
return this.initMargin;
}
setMarginInit(n: number) {
this.initMargin = n;
}
getLevrages() {
return this.initLevrage.map(x => x);
}
getTimes() {
return this.timeFrames.map(x => x);
}
getTimeName(i: number) {
log(typeof this.initLevrage);
let t = this.timeFrames[i];
return this.checkFrameType(t);
}
getTimeIndex(name: ITimeFrameTypes) {
let t = this.timeFrames.indexOf(name);
return t;
}
}优点:
缺点:
当你在TypeScript类方法中遇到this上下文丢失的问题时,最常见和推荐的解决方案是使用箭头函数作为类属性。它提供了一种简洁、自动且可靠的方式来确保this始终指向类的实例。
如果对内存开销有严格要求,或者希望方法能够通过原型链继承和共享,那么在构造函数中进行bind操作也是一个有效的选择。
理解this的工作原理是编写健壮JavaScript/TypeScript代码的关键。通过恰当地管理this上下文,可以避免运行时错误,并使代码更具可预测性。