I have a class that has a member-variable name and a function getdata(). The function makes an API call and assigns the value it receives to the member variable
class Person
{
constructor()
{
this.name = this.getdata();
}
getdata()
{
$.ajax({
url: 'https://randomuser.me/api/',
dataType: 'json',
success: function(data) {
console.log(data);
this.name = data;
}
});
}
}
But the value is not assigned.
I have also tried fetch:
class Person
{
constructor()
{
this.name = this.getdata();
}
getdata()
{
fetch('https://randomuser.me/api/').then(function(response) {
return response.json();
}).then(function(j) {
this.name = j
});
}
}
But it does not identify this inside the then function