【发布时间】:2018-07-17 02:31:12
【问题描述】:
我有一个类,它有一个成员变量 name 和一个函数 getdata()。 该函数进行 API 调用并将其接收到的值分配给成员变量
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;
}
});
}
}
但是没有赋值。
我也尝试过获取:
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
});
}
}
但它并没有在 then 函数中识别这个
【问题讨论】:
-
我也尝试过在成功块中使用 return 语句而不是 this.name
-
要“关闭”选民:这很可能是其他东西的复制品。但它提出的问题与链接的问题不同,并且那里的解决方案没有回答这个问题。
标签: javascript ajax fetch-api