[英]TypeScript getting wrong this scope
我知道this
范围,但我不熟悉TypeScript和JavaScript中的类。 我试图访问绑定到类属性的函数中的类属性(更具体地说,它绑定到Socket对象)。
export class BrawlStarsClient {
credentials:object
dataBuffers:Array<Buffer>
pingInterval:number
constructor(credentials:object, options:object = null) {
if (!credentials) throw new Error('No credentials have been passed to constructor')
this.credentials = credentials
// Setup socket
this.client = new Socket()
this.client.on('connect', this.onConnect)
}
onConnect():void {
// In this function this refers to the socket object which is not desired
this.dataBuffers = []
this.pingInterval = null
const initPacket = packetBuilder.buildLoginPacket(this.credentials)
this.client.write(initPacket)
}
}
在onConnect()
这指的是套接字对象而不是类。 我试过的是将onConnect函数重写为箭头函数,但这也无济于事:
onConnect():void {
onConnect = ():void => {
我的问题:
如何在onConnect()函数中访问我的类属性?
你可以使用.bind
。 .bind
会将参数传递给内部函数。
this.client.on('connect', this.onConnect.bind(this));
或箭头功能。 您将手动必须在此处传递参数。
this.client.on('connect', () => this.onConnect());
在constructor
绑定this
:
this.onConnect = this.onConnect.bind(this);
从MDN文档 :
bind()
方法创建一个新函数,在调用时,将其this
关键字设置为提供的值[。]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.