This question has already been answered:
- Loss of context call 5 responses
import ws = require('ws'); export class Server { public static instance:Server; private _webSocketServer: ws.Server; // подключенные клиенты private _clients: { [id: number]: ws; } = { }; constructor() { if (Server.instance !== null && Server.instance !== undefined) throw new Error('singleton'); Server.instance = this; this._webSocketServer = new ws.Server({ port: 8081 }); this._webSocketServer.on('connection', this.onUserConnect); this._webSocketServer.on('error', this.onError); } private onUserConnect(client:ws): void { var id:number = Math.random(); this._clients[id] = client; console.log("новое соединение " + id); //client.on('close', ServerGame.instance.onUserDisconnect); client.onclose = this.onUserDisconnect; client.onmessage = this.onUserMessage; } I decided to make the nodejs server into typescript and divide everything by OOP into classes. I wrote such code in the typescript in the constructor, everything is fine ... _clients is initialized, but as soon as I get to onUserConnect, then _clients is undefined like the onUserConnect method, for example. Those. The feeling that I got into another empty object is somehow. not the class instance where it was. There are two questions here:
Is my mistake here (I'm new)? and how to fix everything in such a scheme?
Maybe there is a better approach where you can make a good OOP structure without such problems.
I tried to refer through a singleton and everything worked, but it's kind of dirty (Thanks in advance for your help!