问题描述
限时送ChatGPT账号..我正在尝试基于 JavaScript 编写一个 ChatClient,并想在onopen"或onmessage"函数(如this.some()")中调用一些其他对象方法.怎么了?
I am trying to write a ChatClient based on JavaScript and want to call some other object methods inside 'onopen' or 'onmessage' functions like 'this.some()'. What's wrong?
var ChatClient = function() {
this.me = null; // This user
this.others = []; // Other users
this.socket = null;
this.handshake = function() {
this.socket = new WebSocket("ws://" + "localhost" + ":8000");
// Error occurred
this.socket.onerror = function(error) {
console.log('Socket error: ' + error);
};
// Opened
this.socket.onopen = function() {
console.log('Socket opened');
this.some(); // <== Error: this.some is undefined
};
// Message received
this.socket.onmessage = function(message) {
console.log('Socket message: ' + message.data);
};
// Closed
this.socket.onclose = function(message) {
console.log('Socket message: ' + message.data);
};
};
this.someOther = function() {
alert('name');
}
this.some = function() {
this.someOther();
}
}
推荐答案
您正试图在异步调用中访问 this
,当套接字打开时该调用不会出现.这会导致 this.some() 未定义.
You are trying to access this
inside the asynchronous call which will not be present when socket will be open. And this cause this.some() to be undefined.
下面的代码应该可以工作:
Below code should work:
var ChatClient = function() {
var _self = this; // Save outer context
this.me = null; // This user
this.others = []; // Other users
this.socket = null;
this.handshake = function() {
this.socket = new WebSocket("ws://" + "localhost" + ":8000");
// Error occurred
this.socket.onerror = function(error) {
console.log('Socket error: ' + error);
};
// Opened
this.socket.onopen = function() {
console.log('Socket opened');
_self.some(); //It should work
};
// Message received
this.socket.onmessage = function(message) {
console.log('Socket message: ' + message.data);
};
// Closed
this.socket.onclose = function(message) {
console.log('Socket message: ' + message.data);
};
};
this.someOther = function() {
alert('name');
}
var some = function() {
this.someOther();
}
}
您调用 this.some() 的方式的问题是 this
的引用已经从 ChatClient
的上下文更改为 WebSocket.open
方法.如果你想使用外部上下文,你需要将上下文存储在某个变量中.例如:_this 或 self;
The problem in the way you are calling this.some() is that the reference of this
has already been changed from the context of ChatClient
to WebSocket.open
method. Stll if you wan to use the outer context you need to store the context in some variable.eg: _this or self;
var _self = this;
然后使用_self.some调用外部函数或变量.
And then use _self.some to call the outer functions or variables.
PS:已编辑答案,请检查:)
PS: Edited the answer please check :)
这篇关于WebSocket 的“onopen()"函数内的对象方法调用给出“函数未定义"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
更多推荐
[db:关键词]
发布评论