Transforming traditional Javascript syntax into arrow function syntax

Seeking to utilize this example without relying on jquery or any other libraries.

The following code is in place:

let xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = function() {...}

This code uses the old style function().

How can I convert this to arrow function syntax?

let xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = () => {...}

I tried this but it did not work. Am I close, or am I approaching this incorrectly? Once again, I aim to complete this exercise without using external libraries.

Answer №1

One issue with arrow functions is that they retain the this context of the enclosing scope.

In your initial example, the this reference would be bound to the XMLHttpRequest object rather than the window.

To address this in arrow notation, you can either refer to the XMLHttpRequest using an outer name like xmlHttp, or bind it to the callback function:

let xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = ((request) => {...}).bind(undefined, request);

https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Function/bind

It's important to note that arrow functions cannot have their this context overridden using methods such as bind, call, or apply.

Answer №2

Bellian's code above is visually appealing, but the .bind(undefined, request); complicates it.

There is an alternative method that ensures synchronization with the expected answer to your questions:

I strongly suggest you follow this approach instead. By using an arrow function, you eliminate direct references to this, allowing for better accessibility to the results. Try running console.log(x) without the .target and see for yourself.

You can also:

let xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = x => {
  let result = x.target;

        if(result.readyState == 4 && result.status == 200){         
            console.log(result.responseText);
            
        }
    
};

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

Detecting collisions between images that have been rotated using CSS animations

My project involves using CSS animations and jQuery to create a simulation of cars moving at a crossroads from a top-down perspective for a driving license quiz. Users must select the order in which the cars will cross by clicking on them. Sample Image: ...

Checking if the current time falls within a specific time range, without taking the year into account, using Javascript

I am looking to add a special feature using JavaScript. I would like to change the background images of my webpage to ones related to Christmas during the holiday week, and have it repeat every year. How can I determine if the current date and time fall ...

Rendering in Three JS involves efficiently utilizing one buffer to display the output within itself

I have been struggling with a particular issue and I really need some assistance: In my three js context, I have created a custom material and rendered it into a texture. ` /* Rendering in texture */ fbo_renderer_scene = new THREE.Scene(); fbo_r ...

transform data into JSON format and transmit using jquery ajax

I have one object: var myobject = {first: 1, second: {test: 90}, third: [10, 20]}; and I need to convert it into a JSON string using jQuery ajax. Can someone please advise on how to achieve this? (I tried using JSON.stringify(), but it didn't work ...

Incorporating external scripts into Angular HTML templates

I recently upgraded to a premium version of Polldaddy and received a script tag for embedding (without the correct id). <script type="text/javascript" charset="utf-8" src="http://static.polldaddy.com/p/0000000.js"></script> I am trying to loa ...

DOM doesn't reflect changes to nested object when component prop is updated

I have a complex object structured in a multidimensional way that appears as follows: obj: { 1: { 'a' => [ [] ], 'b' => [ [] ] }, 2: { 'x' => [ [], [] ] } } This object is located in the r ...

How to use javascript/html to differentiate between male and female names?

I've developed a random name generator code that is powered by both CSS and JavaScript. Currently, the code allows me to input any name - regardless of gender - press the generate button, and receive a randomly generated first and last name. However, ...

Getting the most out of geometry vertices with Threejs: mastering partial transforms

In my current project, I am working with a mesh that consists of approximately 5k vertices. These vertices have been merged from multiple geometries into a flat array. Initially, I was able to modify individual vertices successfully by setting the flag `ve ...

Display radio buttons depending on the selections made in the dropdown menu

I currently have a select box that displays another select box when the options change. Everything is working fine, but I would like to replace the second select box with radio buttons instead. Can anyone assist me with this? .sub{display:none;} <sc ...

The Angular application is experiencing issues following an update from version 11 to version 12

I recently updated my Angular project following these steps: npm cache clean --force npm uninstall @angular/cli@latest @angular/core@latest npm install -g @angular/cli@latest @angular/core@latest After completing the above steps, I proceeded to delete th ...

Javascript SQL query not returning the expected multiple rows, only returning one instead

I have a table containing multiple rows of test results, each row includes the ID of the test taker. Using the logged-in user information, I've added additional rows to the table to ensure accuracy. However, when printing the result to the console, on ...

Issue with external variable not being updated properly in success callback

Working through an array of data, I make updates to a variable called commentBody during each iteration. However, even though the variable is modified within the loop itself, whenever I try to access it from inside a success callback, it consistently show ...

Set a maximum height for an image without changing its width dimension

I am facing an issue with an image displayed in a table. The image is a graph of profiling information that can be quite tall (one vertical pixel represents data from one source, while one horizontal pixel equals one unit of time). I would like to set a ma ...

How can you make sure that mouse events pass through the KineticJS stage?

Is it possible to have a PanoJS3 component covering the entire screen with a KineticJS stage on top, but still allow touch events to pass through the KineticJS stage to what lies beneath? I want shapes on the stage or layer to receive the touch events, wh ...

Utilize Laravel in conjunction with AngularJs by implementing a base path in place of the current one when using ng-src

Let me try to explain my issue clearly. I am delving into using angularJs in my Laravel project for the first time. The controller is responsible for fetching the uploaded photos from the database. public function index() { JavaScript::put([ ...

jQuery shorthand conditional statements

I currently have a jQuery function that is triggered by two separate buttons. $("#btnSearch, #btnDirectorSearch").click(function () { The construction of the HTML output within this function relies on which button was clicked. To accomplish this, I am ut ...

Tips for creating a stylish navbar with a faded effect on the right side and integrating a fresh button into its design

I'm looking to enhance my Navbar by implementing a feature where, if the width of the Navbar exceeds that of its parent div, it will fade on the right side and a new button will be added - similar to what can be seen on Youtube. 1- When the Navbar&ap ...

"Is it possible to create a single-page website with a unique logo for each div

Is it possible to have a unique logo on each section of my single-page website? Each section has its own div. Check out my website at . Thank you in advance! ...

React component failing to update when props change

After loading correctly, my react component fails to re-render when props change. Despite the fact that render() is being called and the list array contains the correct data according to console.log(list), the page does not refresh. Adding a setState in co ...

Is it possible to pass a component into a dialogue box in material-ui using React?

Hello, I am currently facing an issue with displaying a chart component within a dialogue box. Despite having the code in place, the chart is not rendering inside the dialogue box as expected. Unfortunately, due to the complexity of the code, I am unable t ...