我有一个 javascript 类来管理我的 API 调用(此处为 TimelinesManager),并且我需要在 XMLHttpRequest.onload 内调用我的管理器(同一类,名为 arrayToObject)的方法。
我尝试使用 this.arrayToObject() 和 TimelinesManager.arrayToObject() 访问它,但收到错误消息,表示它不是函数(TypeError:this.arrayToObject 不是函数)。
class TimelinesManager {
getTrends(access_token, start, limit, callback) {
// Create a request to API
var request = new XMLHttpRequest();
request.open('GET', 'https://api.extopy.com/timeline/trends.php', true);
request.onload = function () {
var data = JSON.parse(this.response);
if (request.status == 200) {
// Here I try to access to my class method
callback(this.arrayToObject(data));
}
};
request.send();
}
// The method I want to call
arrayToObject(data) {
// Here I proceed my data
}
}
如何访问该类方法?
最佳答案
试试这个。我们需要将其放入变量中。在请求中 this
指的是请求
class TimelinesManager {
getTrends(access_token, start, limit, callback) {
// Create a request to API
let self = this;
var request = new XMLHttpRequest();
request.open('GET', 'https://api.extopy.com/timeline/trends.php', true);
request.onload = function () {
var data = JSON.parse(this.response);
if (request.status == 200) {
// Here I try to access to my class method
callback(self.arrayToObject(data));
}
};
request.send();
}
// The method I want to call
arrayToObject(data) {
// Here I proceed my data
}
}
关于javascript - 如何访问 XMLHttpRequest 中的类方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53990396/