Javascript WebSocket内部的对象方法调用';s';onopen()';函数给出';函数未定义';
我正在尝试编写一个基于JavaScript的ChatClient,并希望调用“onopen”或“onmessage”函数中的其他一些对象方法,如“this.some()”。怎么了Javascript WebSocket内部的对象方法调用';s';onopen()';函数给出';函数未定义';,javascript,websocket,Javascript,Websocket,我正在尝试编写一个基于JavaScript的ChatClient,并希望调用“onopen”或“onmessage”函数中的其他一些对象方法,如“this.some()”。怎么了 var ChatClient = function() { this.me = null; // This user this.others = []; // Other users this.socket = null; this.handshake = function()
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();
}
}
var ChatClient=function(){
this.me=null;//此用户
this.others=[];//其他用户
this.socket=null;
this.handshake=函数(){
this.socket=newwebsocket(“ws://“+”localhost“+”:8000”);
//发生错误
this.socket.onerror=函数(错误){
log('套接字错误:'+错误);
};
//打开
this.socket.onopen=函数(){
log(“套接字已打开”);
this.some();//您试图访问异步调用中的this
,当套接字打开时,该调用将不存在。这会导致未定义此.some()
下面的代码应该可以工作:
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
method.Stll如果要使用外部上下文,则需要将上下文存储在某个变量中。例如:\u this或self
var _self = this;
然后使用self.some调用外部函数或变量
PS:编辑了答案,请检查:)是的,我可以接受这个原因。但是我可以在“onmessge”中设置变量“me”,这是怎么可能的?在这种情况下,你需要记住这一点。var\u self=this;
然后使用\u self
而不是这个来访问变量。谢谢,它可以工作!但是我真的需要吗在try-catch块中创建webSocket?我对webSocket的工作不太了解。但是,如果它似乎在将来的任何时候抛出错误,并且您知道如果发生错误,您可以做什么。请将其放入try-catch:)