javascript - 是否可以从 JavaScript 中的嵌套处理程序方法访问类方法?

标签 javascript ajax xmlhttprequest

我想使用 JavaScript 向服务器发送 XMLHttpRequest。在处理程序函数中,我需要调用周围类的方法。有没有办法实现这一点?

我知道在 JavaScript 中使用 this 有点棘手。因此,我尝试了使用 thisbind(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/

相关文章:

javascript - MongoDB 脚本加载正确,但不工作

javascript - 填充 HTML 下拉列表 onclick

javascript - 将 ajax String 数据转换为数组以更新 ploty 数据

javascript - Javascript-即时串流音频(Web Audio API和XHR)

javascript - 未捕获的类型错误 : Cannot set property 'response' of undefined

javascript - XHR 仅请求 header

java - Spring MVC <input :form> does not allow name attribute to be used. 在使用 javascript document.getElementsByName() 时造成阻碍?

javascript - nodejs读取文件,写入临时文件然后复制并替换原文件

javascript - 如何正确解析和使用promise.all()

Ajax 更新程序中的 Javascript 变量