Hi all,
I'm quite new to Javascript and come from a Java background. I'm trying to understand how the scope of variables works with Javascript objects.
I've written the following websocket code and so far the openMessage-method works as expected: it sends "hello" to the server.
Also the handleMessage-method works partially, messages do enter the switch-case, but sending a message back from the method does not work, nor do I get an exception. I tried to print out the value of the "this.websocket" in the case "echo" and found that it's not null, but does it really refer to the member variable websocket?
Code:MessageControl control = new MessageControl(); control.start(); //.... function MessageControl() { this.websocket = null; MessageControl.prototype.start = function() { var self = this; this.websocket = new WebSocket("some url", "some context"); this.websocket.onopen = this.onOpen; this.websocket.onmessage = function(message) { self.handleMessage(message.data); } } MessageControl.prototype.onOpen = function() { this.send("hello"); // this is actually websocket --> works! }; MessageControl.prototype.handleMessage = function(msg) { switch (msg) { case "echo": this.websocket.send("hello back"); // nothing happens! break; case "something": // do something break; default: console.log("got message: " + msg); } } }


Reply With Quote
Bookmarks