How to make an iterator out of an ES6 class

后端 未结 6 1167
挽巷
挽巷 2021-01-30 10:21

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]

<
6条回答
  •  感情败类
    2021-01-30 10:53

    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)
    

提交回复
热议问题