user5321531 user5321531 - 3 months ago 21
Javascript Question

How to make an iterator out of an ES6 class

How would I make an iterator out of an ES6 class in the same manner as JS1.7

SomeClass.prototype.__iterator__ = function() {...}
syntax?

[EDIT 16:00]

The following works:

class SomeClass {
constructor() {
}

*[Symbol.iterator]() {
yield '1';
yield '2';
}

//*generator() {
//}

}

an_instance = new SomeClass();
for (let v of an_instance) {
console.log(v);
}


WebStorm flags
*[Symbol.iterator]()
with a 'function name expected' warning directly following the asterix, but otherwise this compiles and runs fine with Traceur. (Note WebStorm does not generate any errors for
*generator()
.)

Answer

Define a suitable iterator method. For example:

class C {
  constructor() { this.a = [] }
  add(x) { this.a.push(x) }
  [Symbol.iterator]() { return this.a.values() }
}