I am aware of this scopes but I am new to TypeScript and classes in JavaScript. I am trying to access class properties within a function which is bound to a class property (to be more specific it's bound to a Socket object).
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)
}
}
In onConnect() this refers to the socket object instead of the class. What I've tried is rewriting the onConnect function to an arrow function, but that didn't help either:
onConnect():void { became onConnect = ():void => {
My question:
How can I access my class properties inside of my onConnect() function?