javascript - 如何通过回调和匿名函数将 'this' 保留在范围内?

标签 javascript ecmascript-6

我正在尝试将一些 JSON 加载到 JavaScript 类中,并将 JSON 中的一些属性分配给该类实例上的属性,但我在“this”和作用域方面遇到了问题。我很确定该解决方案涉及箭头函数,但我不知道如何将它们组合在一起。

这是我到目前为止所拥有的:

class Test {

    constructor(url) {
        this.loadJSON(url, this.init);
    }

    loadJSON(url, callback) {
        let xhr = new XMLHttpRequest();
        xhr.open('GET', url);
        xhr.responseType = 'json';
        xhr.onreadystatechange = function() {
            if (xhr.readyState === 4 && xhr.status === 200) {
                callback(xhr.response);
            }
        };
        xhr.send(null);
    }

    init(response) {
        console.log(response.description);
        // this is undefined
        this.description = response.description;
    }

}

在 init() 方法中,console.log 按我的预期工作,但我无法将任何内容分配给对象 - 我只是不断收到“这是未定义的”。

最佳答案

修改你的回调(xhr.response);代码如下:

callback.call(this, xhr.response);

或者,修改 this.loadJsON 代码,如下所示:

this.loadJSON(url, this.init.bind(this)); 

这是完整的解决方案:

class Test {


        constructor(url) {
            this.that = this;
            this.loadJSON(url, this.init);
//Or, this.loadJSON(url, this.init.bind(this)); In that case you dont have to modify "callback(xhr.response);" code
        }

        loadJSON(url, callback) {
            let xhr = new XMLHttpRequest();
            xhr.open('GET', url);
            xhr.responseType = 'json';
            xhr.onreadystatechange = function() {
                if (xhr.readyState === 4 && xhr.status === 200) {
                    callback.call(this, xhr.response);
                }
            };
            xhr.send(null);
        }

        init(response) {
            console.log(response.description);

            this.description = response.description;

            console.log(this.description);

        }

    }

    let t = new Test('MY URL');

关于javascript - 如何通过回调和匿名函数将 'this' 保留在范围内?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48998388/

相关文章:

javascript - AngularJs - 结合 ng-bind : literal (i18n) + $scope element

node.js - 如果我只将 TypeScript 与 Node 一起使用,我可以将它转换为 ES6 吗?

javascript - 如何将 yield (generators) 与 selenium webdriver promises 一起使用?

javascript - 用于设置实例属性的 ES6 类构造函数快捷方式

javascript - 在 JQuery Mobile Slider 上指定间隔

javascript - 使用socket-io制作一个基本的聊天应用程序

javascript - 服务器端的哄骗

javascript - 为什么不对对象属性使用闭包?

javascript - 访问node.js中另一个类的构造函数值

javascript - DRY jsx 渲染方法