Is there a way to have lexical `this` in methods using the ES6 shorthand method notation?

落花浮王杯 提交于 2019-12-02 04:09:50

The ideal solution to your problem would be to use the proper tool for the job: a generator function. They too can be used with a shorthand syntax, and they will properly bind this.

Generator functions return objects which conform to the iterator protocol, and can use yield* to delegate the output of the iterator to another iterable object (like an array).

class Graph {
  constructor(initialNodes) {
    this.data = [...initialNodes];
  }

  * [Symbol.iterator]() {
    yield* this.data;
  }
}

const graph = new Graph([1, 2, 3]);
for (const node of graph) {
  console.log(node);
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!