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
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);
}