1

I tried to load a JSON file inside a js class. The loaded data is available ony inside the function.

 class MakePage {
     constructor() {
        var request=new XMLHttpRequest();
        request.open('GET','daten.json');
        request.responseType='json';
        request.send();
        request.onload=function() {
            this.daten=request.response;
            alert(this.daten[1].Name); // this works
        }       
    }
    test(name) {
        document.getElementById(name).innerHTML=this.daten[1].Name;
    }
}

page=new MakePage();
page.test("xyz"); //  TypeError: this.daten is undefined

How can I store the loaded data in a class member?

EDIT: Thanks for the answers. I tried self=this, bind(this) and the arrow operator, but I always get the same TypeReference error.

4 Answers4

0

Just replace your callback function by an arrow function. When you do this:

this.daten=request.response

this is not what you think it is ;) Using an arrow function won't alter the value of this and it will actually be what you expect.

class MakePage {
     constructor() {
        var request=new XMLHttpRequest();
        request.open('GET','daten.json');
        request.responseType='json';
        request.send();
        request.onload = () => {
            this.daten=request.response;
            alert(this.daten[1].Name); // this works
        }       
    }
    test(name) {
        document.getElementById(name).innerHTML=this.daten[1].Name;
    }
}

Another way to do this is to use bind.

    request.onload=function() {
        this.daten=request.response;
        alert(this.daten[1].Name); // this works
    }       
    request.onload = request.onload.bind(this);

And don't forget to read the doc to understand how it works under the hood: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this

sjahan
  • 5,720
  • 3
  • 19
  • 42
0

The this inside your request.onload=function() refers to the wrong scope.

Either use an arrow function like request.onload = () => {} (recommended), or save a reference to the outer scope by doing const self = this somewhere in the constructor.

Xceno
  • 903
  • 9
  • 22
0

You should maybe try to replace

request.onload=function() {
    this.daten=request.response;
    alert(this.daten[1].Name); // this works
} 

by an arrow function

request.onload=()=> {
    this.daten=request.response;
    alert(this.daten[1].Name); // this works
} 
EGNdev
  • 40
  • 8
0

Just try with a reference to this in the callback function:

 class MakePage {
     constructor() {
        var request=new XMLHttpRequest();
        request.open('GET','daten.json');
        request.responseType='json';
        request.send();
        self=this;
        request.onload=function() {
            self.daten=request.response;
            alert(self.daten[1].Name); // this works
        }       
    }
    test(name) {
        document.getElementById(name).innerHTML=this.daten[1].Name;
    }
 }
Francesco
  • 130
  • 6