I am new to JavaScript and have a good knowledge of C++. I want to store a callback function in a class and call it using the attribute in which it is stored:
class Connection
{
#web_socket = 0;
#log_text = null;
constructor(url, log_callback)
{
this.#web_socket = new WebSocket(url);
this.#web_socket.binaryType = "arraybuffer";
this.#web_socket.onopen = this.onOpen;
this.#log_text = log_callback;
}
onOpen(event)
{
this.#log_text('Connection opened.');
}
}
function displayConnectionState(state_message)
{
document.getElementById('connection-state').innerHTML = state_message;
}
let connection = new Connection("ws://192.168.1.1:80", displayConnectionState);
But I get the following error: "Uncaught TypeError: Cannot read private member #log_text from an object whose class did not declare it at WebSocket.onOpen".
I searched on the web and suppose that the problem is that "this" does not refer to my Connection object. How do I solve that?