Search code examples
javascriptajaxxmlhttprequestarrow-functions

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.


Solution

  • 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)