类成员函数中私有成员变量显示undefined的原因排查
问题分析:类方法中this指向丢失导致的TypeError
类定义与错误场景
首先看提供的TypeScript类代码:
class MyClass { private keysPressed: string[] = []; configure() { window.addEventListener('keyup', this.handleKeyUp); } handleKeyUp(e: KeyboardEvent) { this.keysPressed.push(e.key); } }
执行以下代码时会抛出TypeError: Cannot read properties of undefined (reading 'push'):
const instance = new MyClass(); instance.configure();
原因解释
- 在
configure方法中,你通过instance.configure()调用它,此时方法内的this指向MyClass的实例对象,所以能正常访问this.keysPressed。 - 但当你把
this.handleKeyUp作为回调传给window.addEventListener时,方法的调用上下文被改变:浏览器触发keyup事件时会直接调用handleKeyUp函数,此时函数内的this不再指向MyClass实例——TypeScript默认启用严格模式,这种场景下this会变成undefined。这就导致this.keysPressed等价于undefined.keysPressed,自然抛出错误。
解决方法
有几种常见的修复方式:
- 用箭头函数包裹回调,绑定实例this
修改configure方法:
configure() { window.addEventListener('keyup', (e) => this.handleKeyUp(e)); }
箭头函数不会创建自己的this,它会继承外层作用域(此处configure方法的this指向实例)的this。
- 在传递回调时用bind绑定实例this
configure() { window.addEventListener('keyup', this.handleKeyUp.bind(this)); }
bind会返回一个新函数,强制让函数内的this始终指向传入的MyClass实例。
- 将handleKeyUp定义为类箭头方法
直接在类里用箭头函数定义方法,让方法内的this永久绑定到类实例:
class MyClass { private keysPressed: string[] = []; configure() { window.addEventListener('keyup', this.handleKeyUp); } handleKeyUp = (e: KeyboardEvent) => { this.keysPressed.push(e.key); } }
内容的提问来源于stack exchange,提问作者Mike K
相关产品推荐
相关产品推荐

