Javascript嵌套对象和“ this”

时间:2019-02-14 13:44:54

标签: javascript oop

我正在定义一个Javascript类,该类包含一个对象,该对象具有修改上层对象的方法。我想这已经被问到并回答了,但是经过大量阅读和搜索,我没有找到适合我的情况的答案。我对高级javascript OOP不太有经验。

因此,这是我的情况,首先我编写通用语法,而不是Javascript来显示我的需求。在我的第一个版本中,我在UserChat()函数中定义了wSocket事件,但结果类似。为了能够在chat.addMessages函数体内引用和使用wSocket.onmessage,我该怎么做?

我无法向this.wSocket.onmessage = function (event)添加参数作为对原始WebSocket方法的引用。

Class ChatSocket
{
    var chat as UserChat;
    var wSocket as WeSocket;

    wSocket.onmessage = function (event)
    {
        //HERE IS THE PROBLEM, "this" is not what I need in here
        this.chat.addMessages(event.data); 
    }
}

Class UserChat
{
    var chatId;
    var messages[];
    var wSocket;

    function addMessages(){};
}

这是我的javascript版本:

function ChatSocket(userChat, userToken)
{
    this.userChat = userChat;
    this.userToken = userToken;
    this.wSocket = new WebSocket("ws://127.0.0.1:8080");

    this.wSocket.onmessage = function (event)
    {
            this.userChat.addNewMessages(event.data);
    }

    this.wSocket.onopen = function()
    {
        this.wSocket.send('hello');
    }

    this.wSocket.onerror = function(error)
    {
        console.error('>>> Error...');
    }
}
//----------------------------------
function UserChat(chatId)
{
    this.chatId = chatId;
    this.lastMessageId = 0;
    this.wSocket = false;

    this.refreshByTcp = function(userToken)
    {
        if (this.wSocket === false)
        {
            this.wSocket = new ChatSocket(this, userToken);
        }
         else
        {
            this.wSocket.send('poll');
        }
    }
}

0 个答案:

没有答案