I admit that I’ve already asked a question about the this keyword and what it means in certain situations, but I still do not completely understand it I’m afraid. Any hints would be greatly appreciated.
I basically have a Socket class, which is a wrapper to the WebSocket class of HTML5 to make things easier (I only copied what is relevant to my question):
var Socket = function(url) {
this.url = url;
this.webSocket = null;
}
Socket.prototype.init = function() {
this.webSocket = new WebSocket(this.url);
this.webSocket.onmessage = this.parseMessage;
};
Socket.prototype.parseMessage = function(event) {
console.log(this); // logs the WebSocket (native) instance
}
In the parseMessage function, this refers to the instance of the native WebSocket object, so how can I access the instance to my Socket object here?
Thanks a lot.
You can
bindit:However, not all browsers support this natively, but you can grab a code snippet from MDC to make all browsers compatible.
In you’re unfamiliar with binding … it lets you specify specifically what
thisshould be when that function is called. At the time that line runs,thisis your Socket class instance, so you’re basically forcingthisinside parseMessage to point back to the instance.If, for some reason, you don’t want to use
bind, another option is to save a copy ofthisto a variable so the meaning is not lost inside an event dispatch: