Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript old syntax to arrow function conversion

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.

like image 325
jwknz Avatar asked Sep 18 '26 08:09

jwknz


1 Answers

The problem with arrow functions is that they keep the this object of the outer scope.

Your first example would have the XMLHttpRequest bound to the this reference the second the window

To make this work with arrow notation, you need to reference the XMLHttpRequest with the outer name 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

Be aware that you can not override the this reference of arrow functions by any mean (bind, call, apply)

like image 70
Bellian Avatar answered Sep 19 '26 22:09

Bellian



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!