【发布时间】:2019-06-06 12:09:26
【问题描述】:
我想用 JavaScript 向服务器发送一个 XMLHttpRequest。在处理函数中,我需要调用周围类的方法。有没有办法实现这一点?
我知道 this 在 JavaScript 中的用法有点棘手。所以我尝试了使用this 和bind(this) 的所有排列,但没有成功。
class ServerRequest
{
askServer(url)
{
var request = new XMLHttpRequest();
request.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
// Got the response
this.foo().bind(this); // How to access foo-method??
}
}
request.open('GET', url);
request.send();
}
foo()
{
// Do something here
}
}
我的目标只是达到这个 foo 方法,但 Firefox 控制台向我显示消息“TypeError:this.foo is not a function”。
【问题讨论】:
-
foo.call(ServerRequest);
标签: javascript ajax xmlhttprequest