Monday, May 20, 2024
76
rated 0 times [  80] [ 4]  / answers: 1 / hits: 32994  / 9 Years ago, thu, february 26, 2015, 12:00:00

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


More From » ecmascript-6

 Answers
10

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)

[#67657] Tuesday, February 24, 2015, 9 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
marint

Total Points: 550
Total Questions: 105
Total Answers: 124

Location: Zambia
Member since Sat, Oct 31, 2020
4 Years ago
;