繁体   English   中英

函数回调范围外

[英]Out of scope in function callback

我的客户“类”看起来像这样:

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;
})();

我正在使用websocket.io模块接收来自客户端的消息。 现在,上面的代码可以工作了,但是我真的很想拥有Client.prototype.message_handler ,以便ctor看起来像这样:

function Client(socket)
{
    this.socket = socket;
    this.country_code = null;

    this.socket.on('message', this.message_handler);
}

但是,问题在于现在在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不能解决客户端类。 反正是有传递或者任何this通过功能this.socket.on('message', this.message_handler) 这样,我可以将继承与不同的处理程序一起使用。

使用此处描述的Javascript Function.prototype.bind功能。 您可以执行此操作(由于@ nhaa123的修复而更新):

this.socket.on('message', this.message_handler.bind(this));

然后,套接字的消息处理程序将始终绑定到Client实例。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM