Could a class method be accessed from outside a nested handler method in JavaScript?

I am trying to make an XMLHttpRequest to a server using JavaScript. In the handler function, I need to call a method from the surrounding class. Is there a way to achieve this?

Understanding how this works in JavaScript can be confusing. I have experimented with different permutations of using this and bind(this), but so far, my attempts have been unsuccessful.

class ServerRequest
{
    askServer(url)
    {
        var request = new XMLHttpRequest();
        request.onreadystatechange = function () {
            if (this.readyState == 4 && this.status == 200) {
                // Got the response
                this.foo().bind(this); // How do I access the foo method??
            }
        }
        request.open('GET', url);
        request.send();
    }

    foo()
    {
        // Perform some action here
    }
}

All I want is to be able to call the foo method, but when I try, Firefox Console displays the message "TypeError: this.foo is not a function".

Answer №1

There are two ways to handle this situation.

Option 1: Utilize the arrow function

askServer(url)
{
    var request = new XMLHttpRequest();
    request.onreadystatechange = () => {
        if (request.readyState == 4 && request.status == 200) {
            // Response received
            this.foo(); // How to access foo-method??
        }
    }
    request.open('GET', url);
    request.send();
}

foo()
{
    // Perform operations here
}

In this approach, the request object is referenced through a variable instead of using this, as the arrow function has a different scope binding. You can refer to the request object like this: https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/onreadystatechange#Example

Option 2: Save reference to upper scope in a variable:

askServer(url)
{
    var request = new XMLHttpRequest();
    var self = this;
    request.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {
            // Response obtained
            self.foo(); // How to access foo-method??
        }
    }
    request.open('GET', url);
    request.send();
}

foo()
{
    // Implement functionality here
}

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

Strategies for Ensuring Ember JS Waits for Asynchronous Functions to Respond Prior to Rendering

Currently, I'm tackling a project that came to the company through an outsourced channel. My query concerns the rendering of an image src. In the past, images were served from the filesystem. However, we've now transitioned to using AWS S3 bucke ...

Update the link by simply clicking on a div tag

I am currently working on a PHP page and my goal is to add the extension ?id=variable_value to its URL when I click on a specific div. However, whenever I try to do this, it shows me an error message stating that the URL with the extension is undefined. B ...

Is there a way to stop TinyMCE from adding CDATA to <script> elements and from commenting out <style> elements?

Setting aside the concerns surrounding allowing <script> content within a Web editor, I am fully aware of them. What I am interested in is permitting <style> and <script> elements within the text content. However, every time I attempt to ...

Steps for including a subdocument within a mongoose schema

I am currently working on setting up a subdocument within a mongoose schema using node.js/Express. There are two schemas in play: Member and Address Member.js // app/models/member.js // Loading mongoose to define the model var mongoose = require(' ...

Guidelines for converting a number into an array of strings using JavaScript

Task: Write a function that takes a number and returns an array of strings, each element being the number cut off at each digit. Examples: For 420, the function should return ["4", "42", "420"]; For 2017, the function should return ["2", "20", "201", "2017 ...

Arrange the items in a list in JavaScript in descending sequence

How to sort a list of records in JavaScript in descending order? var number; //dynamic number retrieved from API var test; //dynamic text retrieved from API for (var i; i <= accList.length; i++) { var odlist = 'you have :' + test + number ...

Automatically resizing images in a canvas when their resolution exceeds the canvas size in HTML5

I am currently using Html5, fabric.js, and JavaScript to upload multiple images to a canvas. However, there are instances where the uploaded image size exceeds that of the canvas. I am looking for a way to ensure that the image is set to a fixed size. v ...

Encountering difficulties with updating an object in Angular

Currently, I have the ability to generate objects and store them in a rails database using a json api. The application is a basic todo list where adding an object places it into the todo list above the input fields. Furthermore, I can access all objects on ...

Excessive geolocation position responses in Angular 5

I am trying to implement an Angular 5 component that will continuously fetch my current location every 3 seconds if it has changed. Here is a snippet of my code: export class WorkComponent implements OnInit { constructor(private userService: UserService ...

Empty Media Viewer

I am encountering an issue with setting up a code, as it only displays a blank white page. Any suggestions on what might be causing this problem in the setup and assistance in resolving it would be greatly appreciated. <script type="text/javascript ...

Troubleshooting: Problems with AngularJS $http.get functionality not functioning as expected

I have a user list that I need to display. Each user has unread messages and has not created a meal list yet. I want to make two http.get requests within the main http.get request to retrieve the necessary information, but I am facing an issue with asynchr ...

Encountering Datepicker Issue in Your Angularjs App?

I am currently working on a web application using Angular JS and I encountered an error when trying to incorporate a date picker. The error message displayed is "elem.datepicker is not a function" To implement the datepicker, I found reference code in thi ...

Error: Uncaught promise rejection - The function is undefined in the context of Vue.js and Electron

I've been experimenting with anime.js to animate elements using promise functions. However, I'm encountering an issue where the second function does not run after the previous one successfully completes. <script> import Splash from '. ...

I am unable to utilize the map function as it results in a TypeError: The property 'map' is undefined and cannot be read

I recently delved into the world of "REACT" in order to work on the front-end of my own project. I encountered a problem for 2 days with the map function while getting data from my back-end and saving the IDs in the Cuartos array. I couldn't figure ou ...

Finding the index value of an array in Django

When sending an array of arrays via a POST request using $ajax, the structure is as follows: For example: [[1, "25, 25, 25", "pounds", "exercise note 1"],[2, "", "No Weight", "note 2"]] The ajax ...

Is it possible for a conditional type in TypeScript to be based on its own value?

Is it possible to use this type in TypeScript? type Person = { who: string; } type Person = Person.who === "me" ? Person & Me : Person; ...

Encountering difficulties loading a Partial View using a JQuery ActionResult request in ASP.NET Core

I've been struggling with this issue for what seems like forever. Although I can initiate the ActionResult that returns PartialView("MODEL"), I'm having trouble rendering the actual View into the div within the Index cshtml page. Here's wh ...

Show the error message from passport.js authentication in the user interface

I am currently working on a new project with Sails.js and using Passport.js for user authentication. Despite having the basic authentication set up, I am struggling to display error messages in the login view when incorrect credentials are entered. I have ...

Is it possible for me to include the id attribute in an HTML element that has been generated using React

While working with Selenium to create end-to-end tests for a React-based web application, I noticed that very few HTML elements have the id property set. Since our development team is preoccupied with other tasks, I've taken it upon myself to address ...

Guide to sending multiple images through an upload form using Ajax and Node.js

I need help sending form data to the server side using jQuery.ajax. My requirement involves uploading multiple images. Upon pressing the submit button, I want to send the image paths via ajax to a server running on node.js. However, since I am using a fo ...