调用相同 "class" 的另一个方法,但此上下文在 Javascript 中不同?

Call another method of the same "class" with this context being different in Javascript?

我正在处理 WebSocket 的包装器,我遇到了有关 this 上下文的问题。请注意,我已经通过阅读 Whosebug 文章了解 为什么 问题会发生,但现在 如何 解决它。

这是我现在的 class

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

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

确保 thisonRawMessage 中始终正确的唯一方法(即指向 class 实例)是将其绑定在构造函数中:

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

The problem is that onRawMessage can be being called outside of the class by my program and other developers, and so the this in this.decode() does not point to my class anymore.

在我看来,您不一定有责任确保其他开发人员的代码正常工作。当然,让他们更方便是很好的,但他们也应该期望该方法在没有正确实例的情况下无法工作,因为大多数方法都是这种情况。

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