我想使用 JavaScript 向服务器发送 XMLHttpRequest。在处理程序函数中,我需要调用周围类的方法。有没有办法实现这一点?
我知道在 JavaScript 中使用 this
有点棘手。因此,我尝试了使用 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 不是一个函数”。
最佳答案
您可以通过两种方式处理它。
使用箭头功能
askServer(url)
{
var request = new XMLHttpRequest();
request.onreadystatechange = () => {
if (request.readyState == 4 && request.status == 200) {
// Got the response
this.foo(); // How to access foo-method??
}
}
request.open('GET', url);
request.send();
}
foo()
{
// Do something here
}
正如您所看到的,我现在通过变量而不是通过 this
引用请求对象,因为箭头函数作用域的绑定(bind)方式不同。
您可以在此处查看如何引用请求:
https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/onreadystatechange#Example
将上限引用保存在变量中:
askServer(url)
{
var request = new XMLHttpRequest();
var self = this;
request.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
// Got the response
self.foo(); // How to access foo-method??
}
}
request.open('GET', url);
request.send();
}
foo()
{
// Do something here
}
关于javascript - 是否可以从 JavaScript 中的嵌套处理程序方法访问类方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56477324/