Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/388.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript ES6从回调中返回JS类和此作用域_Javascript_Reactjs_Scope_Ecmascript 6 - Fatal编程技术网

Javascript ES6从回调中返回JS类和此作用域

Javascript ES6从回调中返回JS类和此作用域,javascript,reactjs,scope,ecmascript-6,Javascript,Reactjs,Scope,Ecmascript 6,我在StackOverflow上搜索了StackOverflow这个问题,但还没有找到答案,所以如果已经找到答案,请耐心等待 我在ES6中定义了一个类(使用ReactJS,尽管这与问题有些无关),如下所示。我想从我的fetch回调中修改this.size和this.u缓存,但显然,我无法直接操作“this”,因为它引用的是类实例化以外的另一个对象。当定义要绑定到此的var时,它确实可以引用对象,但我觉得这不是ES6实现这一点的最佳方法: class MyDataListStore {

我在StackOverflow上搜索了StackOverflow这个问题,但还没有找到答案,所以如果已经找到答案,请耐心等待

我在ES6中定义了一个类(使用ReactJS,尽管这与问题有些无关),如下所示。我想从我的fetch回调中修改this.size和this.u缓存,但显然,我无法直接操作“this”,因为它引用的是类实例化以外的另一个对象。当定义要绑定到此的var时,它确实可以引用对象,但我觉得这不是ES6实现这一点的最佳方法:

class MyDataListStore {

    constructor(url) {
        this.url = url;
        this.size = 0;
        this._cache = [];
        this.getRemoteData();
    }

    getRemoteData() {
        var that = this;
        fetch(this.url).then(function(response) {
             return response.json();
        }).then(function(j) {
             that.size = j["total"];
             that._cache = j["table"];
    });
    }
}
我觉得ES6遗漏了一些东西,也许有更好的方法可以做到这一点

谢谢

这应该可以做到:

getRemoteData() {
  fetch(this.url)
  .then((response) => response.json())
  .then((j) => {
     this.size = j.total;
     this._cache = j.table;
  });
}

对不起,我实际上是在构造函数的底部调用它,忘记添加行,现在正在编辑。这对范围有什么影响?在我的初始示例中,“this”绑定到回调,但在这个示例中,它绑定到类对象?@Loic Duros-请先阅读此内容