我知道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()函数中访问我的类属性?
答案 0 :(得分:2)
您可以使用.bind
。 .bind
会将参数传递给内部函数。
this.client.on('connect', this.onConnect.bind(this));
或箭头功能。您将手动在这里传递参数。
this.client.on('connect', () => this.onConnect());
答案 1 :(得分:1)
在this
中绑定constructor
:
this.onConnect = this.onConnect.bind(this);
bind()
方法创建一个新函数,在调用时,将this
关键字设置为提供的值[。]