打电话给#34; class"这个上下文在Javascript中有所不同吗?

时间:2015-08-01 13:26:16

标签: javascript oop reference this

我正在处理WebSocket的包装器,我对this上下文有疑问。请注意,我已经通过阅读StackOverflow文章了解为什么问题,但现在如何来解决它。

这是我目前的课程

MusicArena.JsonWebSocket = function (url, onOpen, onMessage, onError) {
    this.webSocket = new WebSocket(url);
    this.webSocket.onmessage = this.onRawMessage.bind(this); // This is fine

    // This key is used by the decode method, and in the future might get value from a parameter.
    this.encryptionKey = ENCRYPTION_KEY;

    // Other iniitalization code.
};


MusicArena.JsonWebSocket.constructor = MusicArena.JsonWebSocket;

MusicArena.JsonWebSocket.prototype.decode = function (encoded) {
    // Process the encrypted message
};

MusicArena.JsonWebSocket.prototype.onRawMessage = function (event) {
    var data = event.data;
    var decoded = this.decode(data);

    var obj = JSON.parse(decoded);
    if (DEBUG) {
        console.log(obj);
    }

    if (obj) {
        this.onMessage(obj.ID, obj.Action, obj);
    };
};

// Other codes

问题是我的程序和其他开发人员可以在课外调用onRawMessage,因此this中的this.decode()不再指向我的班级。有没有办法在decode内调用onRawMessage而不必让用户绑定JsonWebSocket实例?

1 个答案:

答案 0 :(得分:2)

确保thisonRawMessage总是正确的唯一方法(即指向类实例)是将它绑定在构造函数中:

this.onRawMessage = this.onRawMessage.bind(this);
  

问题是我的程序和其他开发人员可以在课外调用onRawMessage,因此this.decode()中的这个不再指向我的课了。

IMO并不一定要确保其他开发人员的代码正常运行。当然,为它们提供更方便是很好的,但是如果没有正确的实例,它们也应该期望该方法不起作用,因为大多数方法都是如此。

此外,虽然他们当然可以调用该方法,但它似乎没有多大意义,因为它需要一个非常特定的事件对象。如果他们将其称为socket.onRawMessage(...),则this无论如何都会正确指向socket