How to Retrieve Class Member Variables in JavaScript Prototype Functions During Callbacks

Here is my code snippet:

function MyClass(udpSocket)
{
  this.IPSocket = udpSocket;
  this.port;
  this.DestAddr;
}

MyClass.prototype.handleMessage = function(message)
{

 var msg = JSON.parse(message);

    switch(msg.type) 
    {
        case "Send":
        var BufToSend = "Hey";
        this.IPSocket.send(BufToSend, 0, BufToSend.length, this.port, this.DestAddr, function(err, bytes) 
        {
            if (err) throw err;
        });
    break;

MyClass.prototype.setWebSocketConnection = function( ws)
{
    this.wsConnection = ws;


    this.wsConnection.on('message', function incoming(message) 
    {
        MyClass.prototype.handleMessage( message );
    });
}

MyClass.prototype.setUdpPort = function( PORT )
{
    this.port = PORT;
}

MyClass.prototype.setDestAddr = function( DEST_ADDR )
{
    this.DestAddr = DEST_ADDR;
}

exports.mMyClass = MyClass;

The issue arises when I try to access the member variables of MyClass within the handleMessage callback and cannot send a message over udpSocket. Any suggestions on how to solve this problem?

Answer №1

Utilizing a reference to this allows you to access it within a callback function. Check out this straightforward illustration:

var MyObject = function(value) {
  this.value = value;
};

MyObject.prototype.displayValue = function() {
  
  var internalFunction = function(callback) {
    callback();
  };
  
  internalFunction(function() {
    console.log('Attempting to access "this" directly: ', this.value);
  });
  
  var that = this;
  internalFunction(function() {
    console.log('Accessing with the help of a reference: ', that.value);
  });
  
};

var objInstance = new MyObject('hello');

objInstance.displayValue();

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How can I ensure a checkbox remains checked even when the page is reloaded

A clock has been designed based on a unique fantasy timezone. An "alarm" function has also been set up to trigger an alert when a checkbox is checked. Efforts are being made to use local storage to ensure the checkbox remains checked even after the page i ...

Discover the power of AngularJS's ng-route feature for creating a dynamic and seamless one-page HTML template experience

I'm attempting to create a dynamic header using ng-repeat. Here's the initial code: <ul class="right"> <li><a href="#carousel">Home</a></li> <li><a href="#about-us">About Us</a></li> &l ...

Transform the header style columns of react-js Material-tables into rows

Currently experimenting with gradient designs on a material table. While I am able to apply the right color combination to the rows, I seem to be getting column-based results on the title of the table. Attached is a screenshot of my output for reference. ...

"Troubleshooting issue: Unable to retrieve grid data from Google Sheets API v4 when integrated

I've implemented a function within a React component that retrieves JSON data from an API request and logs it: async function getAllSheets() { let response; try { response = await window.gapi.client.sheets.spreadsheets.values.batchGet( ...

What is the significance of the "#" character in the URL of a jQuery mobile

As I encounter a strange issue with my jQuery mobile page, I notice that when accessing page.php everything looks good, but once adding #someDetailsHere to the URL, it only displays a blank white page. What could be causing this and how can I resolve it? ...

Error message: Authentication timestamp issue with cex.io web socket

Currently in the process of connecting to the CEX.IO bitcoin exchange's websocket. The websocket connection itself is fine, but encountering an error during the authentication phase: "Timestamp is not in 20sec range." Unsure about the cause of this is ...

Having the same name for multiple query parameters does not result in an array being returned

Using the link http://example.com/users?test=1&test=2 router.route('/users/?').get((req, res) => { console.dir(req.query) //=> { test : 1 } }) The output is { test : 1 } instead of an expected array [ 1, 2 ]. Even ?test[]=1&test ...

Issue encountered during upgrade from version 10 to version 13 in a Next.js migration: Module not found

I've been working on upgrading our old site from version 10 to version 13, and we have a custom backend built with express. However, I keep encountering a "Module not found" error when running the project concurrently, specifically when running the cl ...

Function in Typescript that accepts an extended interface as a parameter

I am facing an issue with my interface named "Example" which has a function type called "exampleFunction". The problem arises when this function takes a super class as an input parameter because TypeScript is reporting an error. It states that I cannot use ...

The script from 'URL' was declined for execution due to its MIME type of 'text/html' which is non-executable, in addition to strict MIME type checking being enabled

I encountered an error stating "Refused to execute script from 'URL' because its MIME type ('text/html') is not executable, and strict MIME type checking is enabled." The code that triggered this error is shown below. <!DOCTYPE htm ...

Display all dependents associated with a dependency in the lock file

Is there a way to identify all dependents of a specific dependency from a lock file (npm/pnpm/yarn)? This is the opposite of using yarn ls I would rather not parse the lock file if there is an existing command in npm/pnpm/yarn for this I am aware that I ...

I need assistance with this ajax/javascript/php

I am currently working on creating a dynamic chained list. The idea is to have the user make selections from the first four dropdown lists, and based on their choices, a fifth dropdown list should appear. However, I am facing some issues with my code as th ...

Is it possible to invoke a Django view function in JavaScript by using its namespace and function name?

If we want to call a Django view from HTML, we typically use the syntax below: "{% url 'namespace: view_fun' %}" But what about calling it from JavaScript? Your assistance is greatly appreciated! ...

Update the table with information from a designated URL every 5 seconds

So here's the situation: I've got a dynamic HTML table <table id="example"></table>. The data displayed in this table changes according to the URL. Normally, my default URL looks like this: index.php?action=add To handle this, I&a ...

Preventing changes to objects

Currently, I am working on a project using React and ES6. I encountered an interesting scenario recently: I had a state with an array of objects a = [{id: 1, value: 1}, {id: 2, value: 2}] in Object A. Upon passing this list to Object B via props, Object B ...

Problem encountered when attempting to return data received from database queries executed within a loop

Having an issue with making multiple MongoDB queries in a loop and trying to send all the results as one data array. However, simply using 'return' to send the data is resulting in 'undefined' and not waiting for the results of all DB r ...

Is there a way to create a hover effect on a sidebar element?

I'm struggling to add a hover effect to the elements within my sidebar. I've tried using CSS :hover, but it doesn't seem to be working as expected. Any guidance or solution would be greatly appreciated. .sidebar .navbar .nav-link:hover{ ...

Navigating between different pages on datatables with rowspans

I'm encountering a challenge in paginating a datatable with rowspans. The issue arises when setting the "pageLength" attribute, as it includes all trs. For instance, if I have a structure like this, I would need to specify "pageLength: 3". ----------- ...

What is the best way to extract data from a JSON object using JavaScript, Node.js, or React?

The data received from the server includes information on two different products: [{ "model": "G7", "brand": "LG", "price": 999.99, "image": "https://www.bell.ca/Mobility/Products/LG-G7-ThinQ?INT=MOB_mobdevpg_BTN_poplink_Mass_051016_mb_details#", ...

Display a JSON encoded array using Jquery

Within an ajax call, I have a single json encoded array set: $var = json_encode($_SESSION['pictures']); The json encoded array is stored in a variable called "array" When I try to display the contents of "array" using alert, I get this respons ...