我正在进行一个小小的Websockets演示,我有一个范围问题,我无法排序。
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;
};
};
如何从socket.onmessage事件中访问this.setId()?
答案 0 :(得分:2)
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;
};
};
保留这样的引用应该这样做。只要您在函数中引用this
,请将this
替换为self
。