【问题标题】:Is there a possibility to access class method out of a nested handler method in JavaScript?是否有可能从 JavaScript 中的嵌套处理程序方法访问类方法?
【发布时间】:2019-06-06 12:09:26
【问题描述】:

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

我知道 this 在 JavaScript 中的用法有点棘手。所以我尝试了使用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 is not a function”。

【问题讨论】:

  • foo.call(ServerRequest);

标签: javascript ajax xmlhttprequest


【解决方案1】:

你可以通过两种方式处理它。

使用箭头功能

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 引用请求对象,因为箭头函数范围的绑定方式不同。 您可以在此处查看如何引用请求: 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
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-04-04
    • 1970-01-01
    • 1970-01-01
    • 2015-11-16
    • 1970-01-01
    • 1970-01-01
    • 2022-01-18
    相关资源
    最近更新 更多