提问人:javanoob 提问时间:2/14/2021 最后编辑:javanoob 更新时间:2/14/2021 访问量:61
简单的 websocket 库(这在调用时丢失)[重复]
Simple websocket library (this lost on call) [duplicate]
问:
------注意:请参阅本文末尾的解决方案-------
我正在尝试制作一个简单的 websocket 库,它允许在连接时有一个回调,在收到消息时有一个回调,如果 5 秒后没有收到消息,则自动重新连接。
<html>
<script>
function ws(url, cb, concb){
this.timeout = setTimeout(this.timeoutCB, 5000);
this.url = url
this.cb = cb;
this.concb = concb;
this.startConnection()
}
ws.prototype.startConnection = () => {
this.conn = new WebSocket(this.url);
this.conn.onopen = () => {
this.concb()
console.log('Connected ');
}
this.conn.onclose = function() {
console.log('Connection closed ');
}
this.conn.onmessage = (e) => {
console.log('Received From Server: ' + e.data);
clearTimeout(this.timeout);
text = e.data;
this.cb(text);
this.timeout = setTimeout(this.timeoutCB, 5000);
}
}
ws.prototype.send = function(e) {
this.conn.send(e);
}
ws.prototype.timeoutCB = () => {
alert("PRESS OK TO RECONNECT");
this.timeout = setTimeout(this.timeoutCB, 5000);
this.startConnection();
}
w = new ws("127.0.0.1:9000", null, null);
</script>
</html>
我创建了一个方法,以便能够在构造函数和方法中调用它。问题是,当我从构造函数调用时,这不是 ws 对象,而是 .我不知道如何创建一个可以从构造函数和另一个方法(例如startConnection
timeoutCB
this.startConnection
window
startConnection
timeoutCB
-------------------溶液----------------------------------------------------
请查看 Nick Parsons 的评论。这是应用他的建议后对我有用的代码:
function ws(url, cb, concb){
this.url = url
this.cb = cb;
this.concb = concb;
this.startConnection()
}
ws.prototype.startConnection = function() {
this.timeout = setTimeout(() => this.timeoutCB(), 5000);
console.log(this)
this.conn = new WebSocket(this.url);
this.conn.onopen = () => {
this.concb()
console.log('Connected ');
}
this.conn.onclose = () => {
console.log('Connection closed ');
}
this.conn.onmessage = (e) => {
console.log('Received From Server: ' + e.data);
clearTimeout(this.timeout);
text = e.data;
this.cb(text);
this.timeout = setTimeout(() => this.timeoutCB(), 5000);
}
}
ws.prototype.send = function(e) {
this.conn.send(e);
}
ws.prototype.timeoutCB = function() {
alert("PRESS OK TO RECONNECT");
this.startConnection();
}
答: 暂无答案
评论
timeoutCB
setTimeout(this.timeoutCB, 5000);
timeoutCB
this
window
this
setTimeout(this.timeoutCB.bind(this), 5000);
setTimeout(() => this.timeoutCB(), 5000);
() => {}
function() {}
this
this
ws.prototype.timeoutCB = function() {...}
this
window
console.log(this)
ws.prototype.timeoutCB
this
this
this
this