构造函数(JS)中的增量变量

时间:2017-12-03 19:35:20

标签: javascript constructor

我从两个不同的API中获取数据,并且我编写了一个构造函数,它将根据对象创建的新实例启动XMLHttpRequest(如果它有任何意义......)。获取并解析数据后,我想将其保存到不同的命名变量中。例如:trial1data,trial2data。此时,对象的新实例将覆盖数据变量。代码如下:

var api = "http://www.filltext.com/?rows=10&fname={firstName}&lname={lastName}&pretty=true";
var api2 = "http://www.filltext.com/?rows=10&fname={firstName}&lname={lastName}&tel={phone|format}&address={streetAddress}&city={city}&state={usState|abbr}&zip={zip}&pretty=true";

function FetchData(apiType) {
    var r = new XMLHttpRequest();
    this.apiType = apiType;
    this.request = function() {
        r.open("GET", apiType, true);
        r.onload = function() {
        var data = JSON.parse(r.responseText);
        }
        r.send(null);
    }
}

trial1 = new FetchData (api);
trial1.request();

trial2 = new FetchData (api2);
trial2.request();

感谢XMLHttpRequest提示,但问题是将每个数据保存到单独的变量中,例如trial1data和trial2data(或其他任何有意义的东西,我可以在以后重复使用),基于有多少新对象我会创造。

3 个答案:

答案 0 :(得分:1)

您的var r = new XMLHttpRequest();很常见。

每次调用构造函数时,都需要在函数内部移动它以创建单独的请求。

function FetchData(apiType) {

    this.apiType = apiType;
    this.request = function() {

        var r = new XMLHttpRequest();

        r.open("GET", apiType, true);
        r.onload = function() {
           var data = JSON.parse(r.responseText);
           console.log(data);
        }
        r.send(null);
    }
}

答案 1 :(得分:1)

您应该将请求对象创建放在构造函数中:

function FetchData(apiType) {
  var r = new XMLHttpRequest();
  this.apiType = apiType;

  this.done = new Promise( res => {
    r.onload = function() {
      res(JSON.parse(r.responseText) );          
    };
  });
  this.request = function() {
    r.open("GET", apiType, true);
    r.send(null);
  }; 
}

所以你可以这样做:

const req = new FetchData("whatever");
req.request();
req.done.then(console.log);

答案 2 :(得分:-1)

在var r = new XMLHttpRequest()上创建新实例;在构造函数内部,或者作为一种更好的方法,使它成为构造函数的参数,并为每个构造函数注入新的XMLHttpRequets对象。

要回答问题的第二部分,您可以将响应数据存储在对象的属性中并直接访问它或获取接口。而不是

 r.onload = function() {
    var data = JSON.parse(r.responseText);
 }

做类似的事情:

function FetchData(apiType) {

  var self = this;
  this.apiType = apiType;
  this.request = function() {
    var r = new XMLHttpRequest(); 
    return new Promise(function(resolve, reject) {
      r.open("GET", apiType, true);
      r.onload = function() {
        self.data = JSON.parse(r.responseText);
        resolve(self.data);
      }
      r.send(null);
    }   
}

然后

trial1 = new FetchData (api);
var trial1resp;
trial1.request().then(function(data) {
   trial1resp = data;
}

最后一项任务只是为了说明如何存储响应。您必须处理异步处理才能实现目标。

你可以在这里阅读更多关于promisses以及如何处理xhr异步任务https://developers.google.com/web/fundamentals/primers/promises