Search code examples
javascriptecmascript-6ecmascript-harmony

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().)


Solution

  • Define a suitable iterator method. For example:

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

    Edit: Sample use:

    let c = new C
    c.add(1); c.add(2)
    for (let i of c) console.log(i)