Socket.IO的原始'this'上下文

Dan*_*oof 3 javascript prototype socket.io

我在原型类中包装了(客户端)socket.io:

Chat.Client = Class.create();

Chat.Client.prototype = {

    initialize: function() {
        ...
        this.socket.on('message', this.on_message);
        ...
    },

    on_message: function(data) {
        this.add_chat_message(data.something);
    }

    do_something: function(something) {
        ...
    }
Run Code Online (Sandbox Code Playgroud)

这不起作用,因为on_message中的'this'将是'SocketNamespace'.传统上我会通过将'this'作为附加参数传递给回调来解决这个问题,但因为我使用的是socket.io,所以我不能简单地这样做.

我怎么解决这个问题?

Poi*_*nty 10

你可以将它包装在另一个函数中:

initialize: function() {
  // ...
  var client = this;
  this.socket.on('message', function(data) { client.on_message(data); });
Run Code Online (Sandbox Code Playgroud)

在较新的浏览器(或Node.js)中,您也可以在Function原型上使用名为"bind" 的函数:

  this.socket.on('message', this.on_message.bind(this));
Run Code Online (Sandbox Code Playgroud)

"bind"函数返回一个函数,该函数在被调用时将强制以给定值作为this值调用原始函数("on_message").