表題の通りですが、Generator にはいずれの protocol も実装されています。気になるのは iterable の挙動ですが、どうやらレシーバーの Generator 自身を返すようです。

function* count (n) {
	for (;;) yield n++;
}

var c = count(1);
console.log(c.next, c[Symbol.iterator]);
//=> [Function: next] [Function: [Symbol.iterator]]

// iterator protocol
console.log(c.next()); //=> { value: 1, done: false }
console.log(c.next()); //=> { value: 2, done: false }
console.log(c.next()); //=> { value: 3, done: false }

// iterable protocol
console.log(c[Symbol.iterator]().next()); //=> { value: 4, done: false }

console.log(c[Symbol.iterator]() === c); //=> true

iterator protocol (next) で状態をすすめたあとに iterable protocol (Symbol.iterator) で iterator を取得すると、状態は継続されています。

  1. トップ
  2. tech
  3. Generator は iterator であり、iterable でもある
▲ この日のエントリ