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

前端 未结 1 526
暗喜
暗喜 2021-01-23 10:38

First question on SO and I hope I’m not duplicating anything; I’ve looked at other questions and think mine is different enough to warrant asking.

Basically, is there a

相关标签:
1条回答
  • 2021-01-23 10: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);
    }

    0 讨论(0)
提交回复
热议问题