2

How can I pass an arrow function as a variable in a tab ?

I have a function like this :

public handleLogin(data) {
  this.socket.send(data);
  [...]
}

which is in a functions tab :

let tab = [this.handleLogin];

tab[0](data);

But when I call handleLogin by the tab my socket attribute is undefined (seems like 'this' doesn't refers to my class instance but to the function instance so it would not be an arrow function).

What is the correct syntax ?

Artory
  • 845
  • 7
  • 13

1 Answers1

1

Try this

let tab = [(data) => { this.handleLogin(data); }];
tab[0](data);

The arrow function wrapper preserve this context during handleLogin execution.

Kamil Kiełczewski
  • 85,173
  • 29
  • 368
  • 345