I'm working on a little Websockets demo and I've got a scope issue I can't sort.
network = function () {
this.host = "ws://localhost:8002/server.js";
this.id = null;
this.init = function (s) {
var scene = s;
try {
socket = new WebSocket(this.host);
socket.onopen = function (msg) {
};
socket.onmessage = function (msg) {
switch(msg.data[0]) {
case 'i':
var tmp = msg.data.split('_');
// cant access this function.
this.setId(tmp[1]);
break;
}
};
socket.onclose = function (msg) {
};
开发者_运维问答 }
catch (ex) {}
};
this.setId = function(id) {
this.id = id;
};
};
How can I access this.setId() from the socket.onmessage event?
network = function () {
var self = this;
this.host = "ws://localhost:8002/server.js";
this.id = null;
this.init = function (s) {
var scene = s;
try {
socket = new WebSocket(self.host);
socket.onopen = function (msg) {
};
socket.onmessage = function (msg) {
switch(msg.data[0]) {
case 'i':
var tmp = msg.data.split('_');
// cant access this function.
self.setId(tmp[1]);
break;
}
};
socket.onclose = function (msg) {
};
}
catch (ex) {}
};
this.setId = function(id) {
self.id = id;
};
};
preserving a reference like this should do it. anytime you reference this
in a function, replace this
with self
.
精彩评论