Link to home
Start Free TrialLog in
Avatar of Isabell
Isabell

asked on

Why arrow function is not working?

Hi,

This following function works fine.

function loadData() {
  const xhr = new XMLHttpRequest();
  xhr.open('get', 'data.txt', true);
  xhr.onload = function () {
    console.log('ReadyState', this.readyState);
    console.log(this.status);
    if (this.status == 200) {
      document.getElementById('output').innerHTML = `<h1>${this.responseText}</h1>`;
    }
  }
  xhr.send();
}

Open in new window


However, when I use an arrow function for xhr.onload, the code is not working.
any idea why?  Also how should I fix this issue?

function loadData() {
  const xhr = new XMLHttpRequest();
  xhr.open('get', 'data.txt', true);

  xhr.onload = () => {
    console.log('ReadyState', this.readyState);
    console.log(this.status);
    if (this.status == 200) {
      document.getElementById('output').innerHTML = `<h1>${this.responseText}</h1>`;
    }
  }
  xhr.send();
}

Open in new window

Avatar of zc2
zc2
Flag of United States of America image

What browser do you use? It might not be supported.
Avatar of Isabell
Isabell

ASKER

Hi zc2. I am using Chrome browser.
ASKER CERTIFIED SOLUTION
Avatar of zc2
zc2
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Isabell

ASKER

Thanks zc2!
You're welcome!