Object Method Call Inside WebSocket's 'onopen()' Function Gives 'Function Is Undefined'
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 Chat
Solution 1:
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();
}
}
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;
And then use _self.some to call the outer functions or variables.
PS: Edited the answer please check :)
Post a Comment for "Object Method Call Inside WebSocket's 'onopen()' Function Gives 'Function Is Undefined'"