I\'ve create a prototype based class Person
that opens a WebSocket connection and defines callback functions as prototype methods.
Because inside the ca
When you do:
self = this
You are implicitly creating a global variable which (since it's global) will have the same value for all instances. Local variables, must have var
, let
or const
in front of them like one of these:
var self = this;
const self = this;
let self = this;
But, that isn't your solution here. You need to be using this
instead. And, if you're going to supply a callback for the websocket and you want the person associated with that, I would suggest you just put a reference to the Person object on the websocket so you can then retrieve it from there. And, what's with all the missing semicolons to end each statement? Anyway, here is some fixed up code:
function Person(name){
this.name = name;
}
Person.prototype = {
getName : function(){
return this.name;
},
openConnection : function(host, port){
this.pointCount = 0;
this.ws = new WebSocket("ws://" + host + ":" + port);
// save person reference on the web socket
// so we have access to the person from web socket callbacks
this.ws.person = this;
this.ws.onopen = this.onOpenConnection;
},
onOpenConnection : function() {
// "this" will be the websocket
// "this.person" is the person object
console.log(this); // prints the websocket
console.log(this.person); // prints the person
this.send(this.person.name); // works only if one person exists
}
}