[英]Out of scope in function callback
My client "class" looks like this: 我的客户“类”看起来像这样:
var Client = (function () {
function Client(socket)
{
this.socket = socket;
this.country_code = null;
var that = this;
this.socket.on('message', function(data) {
var r = JSON.parse(data);
switch (r.action) {
case 'init':
that.country_code = r.country_code;
break;
}
});
}
Client.prototype.message_handler = function(data)
{
};
return Client;
})();
I'm utilizing websocket.io module to receive messages from clients. 我正在使用websocket.io模块接收来自客户端的消息。 Now, the code above works, but I would really like to have the
Client.prototype.message_handler
, so that the ctor would look like this: 现在,上面的代码可以工作了,但是我真的很想拥有
Client.prototype.message_handler
,以便ctor看起来像这样:
function Client(socket)
{
this.socket = socket;
this.country_code = null;
this.socket.on('message', this.message_handler);
}
However, the problem is that now in the message_handler function 但是,问题在于现在在message_handler函数中
Client.prototype.message_handler = function(data)
{
var r = JSON.parse(data);
switch (r.action) {
case 'init':
this.country_code = r.country_code; // Doesn't work.
break;
}
};
this
doesn't resolve to the Client-class. this
不能解决客户端类。 Is there anyway to pass or whatever this
to the function via this.socket.on('message', this.message_handler)
? 反正是有传递或者任何
this
通过功能this.socket.on('message', this.message_handler)
That way, I could use inheritance with different handlers. 这样,我可以将继承与不同的处理程序一起使用。
Use the Javascript Function.prototype.bind
feature described here . 使用此处描述的Javascript
Function.prototype.bind
功能。 In your case, you can do this (updated thanks to @nhaa123's fix): 您可以执行此操作(由于@ nhaa123的修复而更新):
this.socket.on('message', this.message_handler.bind(this));
Then the socket's message handler will always be bound to the Client instance. 然后,套接字的消息处理程序将始终绑定到Client实例。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.