1

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?

2 Answers 2

2

You can use .bind. .bind will carry the arguments forward to the inner function.

this.client.on('connect', this.onConnect.bind(this));

or a arrow function. You will manually have to pass arguments here.

this.client.on('connect', () => this.onConnect());
Sign up to request clarification or add additional context in comments.

1 Comment

What is the major difference between the two? Are there any advantages or disadvantages for one of them?
2

Bind this in constructor:

this.onConnect = this.onConnect.bind(this);

From the MDN documentation:

The bind() method creates a new function that, when called, has its this keyword set to the provided value[.]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.