Javascript old syntax to arrow function conversion

Viewed 2605

So I want to use this example without jquery or other libraries.

I have this code

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

As you can see it uses the old style function()

How do I change this to an arrow function style one?

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

This doesn't work. Am I close or am I looking at this completely wrong? Again I don't want to use libraries for this exercise.

2 Answers

Bellian's code above looks nice but the .bind(undefined, request); gives the simplicity away.

There's an alternate way of doing this in such a way that it would sync to your questions expected answer:

I highly recommend you should do this instead. The arrow function removed the direct this to gain better access to the results. Check for yourself console.log(x) only without the .target

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);
            
        }
    
};

Related