gpt4 book ai didi

javascript - 我的课可能有什么问题?

转载 作者:行者123 更新时间:2023-11-30 17:29:22 24 4
gpt4 key购买 nike

我正在开发一个类来回调网络套接字:

function QB() {
var ws = null;

this.connect = function () {
// Let us open a web socket
ws = new WebSocket("ws://localhost:9000/koule");

ws.onopen = function () {
if (this.onConnectionEstablished) {
this.onConnectionEstablished();
}
};
ws.onmessage = function (evt) {
var msg = evt.data;
//process callbacks
parseMessage(msg);

};
ws.onclose = function () {
if (this.onConnectionClosed) {
this.onConnectionClosed();
}
};
ws.onerror = function () {
if (this.onConnectionError) {
this.onConnectionError();
}
};
};




this.onConnectionEstablished = null;
this.onConnectionClosed = null;
this.onConnectionError = null;
}

然后我在这个示例中使用它:

<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="qb.js"></script>
</head>
<body>

<h1>My First JavaScript</h1>

<p>Click Date to display current day, date, and time.</p>

<button type="button" onclick="myFunction()">Date</button>

<p id="demo"></p>

<script>
qb = new QB();


qb.onConnectionEstablished = function()
{
alert('connected');
};

qb.onConnectionError = function()
{
alert('error');

};

qb.onConnectionClosed = function()
{
alert('closed');
};


function myFunction() {
qb.connect();
}
</script>

</body>
</html>

我没有收到任何警报,我应该至少收到其中一个。我在 Chrome 中进行了检查,我的 qb 已正确创建,其 ws 变量具有与其 Hook 的回调,并且 qb 具有我设置的回调。

我不明白为什么这不起作用。

谢谢

最佳答案

匿名函数中的 this 范围不是您的 QB 实例的 this:

ws.onopen = function () {
if (this.onConnectionEstablished) {
this.onConnectionEstablished()
}
};

它应该像这样工作:

var self = this;
ws.onopen = function () {
if (self.onConnectionEstablished) {
self.onConnectionEstablished()
}
};

关于javascript - 我的课可能有什么问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23481405/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com