When I am using an arrow function in xhr.onload
, I don't get a response. However, if I use a normal function like xhr.onload = function(){}
then I get the response. Why does the code before not work like it does when using xhr.onload = function(){}
?
let btn = document.getElementById("button");
btn.addEventListener("click" , function(){
let xhr = new XMLHttpRequest();
xhr.open("GET" , "sample.txt" , true);
xhr.onload = () => {
if(this.status === 200){
console.log(this.responseText);
}
}
xhr.send();
})
The context of this of the onload function should be the original XMLHttpRequest, but using the arrow function you don't have a context assigned so the this will more than likely be parent scope or window. That's going to be the issue.