如何将 API 调用中的 return 值分配给 javascript 中的 class 成员变量

How to assign a return value from API call to class member variable in javascript

我有一个 class,它有一个成员变量 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函数里面并没有识别this

您可能想在 JS 中查看 a question on the use of this。您在函数中分配给的 this 不是您所期望的。

最快的解决方法是执行类似

的操作
// ...
getData: function() {
  const self = this;
  fetch(...).then(...
    self.name = j
  )
}

但是使用 arrow functions 也可以解决这个问题。