我想使用方法Reconnection()
作为SetTimeout()
中的回调,而不是类之外的Reconnection()
函数。我已经尝试声明this
作为引用并使用=>
,但是没有成功。
呼叫时:
setTimeout(this.Reconnection, CONFIG.ENTCS_ReconnectionTimer);
我得到:
TypeError [ERR_INVALID_CALLBACK]:回调必须是一个函数”
这是我的代码:
export class CommTcp {
constructor(receivedHost: string, receivedPort: number) {
...
}
//Connect socket and register listeners to socket events
public StartClient() {
...
}
.
.
.
//Handle connection closed -> Start timer for reconnection
HandleClose() {
console.log('CommTcp. Client closed');
setTimeout(this.Reconnection, CONFIG.ENTCS_ReconnectionTimer);
}
//what i want - Not working!!!
Reconnection() {
console.log(`CommTcp. Try to reconnect`);
this.StartClient();
}
}
当我在类外声明函数并将调用更改为:
setTimeout(Reconnection, CONFIG.ENTCS_ReconnectionTimer); //in the class
//Callback function outside the class for handling socket reconnection
function Reconnection() {
let myNewTcp = new CommTcp(CONFIG.ENTCS_IP, CONFIG.ENTCS_PORT);
myNewTcp.StartClient();
}
它可以工作,但不是我想要的
谢谢, 志美