Generator
Generator
객체는 generator function 으로부터 반환된 값이며 이터러블 프로토콜과 이터레이터 프로토콜을 준수합니다.
문법
function* gen() { yield 1; yield 2; yield 3; } var g = gen(); // "Generator { }"
메서드
Generator.prototype.next()
yield
표현을 통해 yield된 값을 반환합니다.Generator.prototype.return()
- 주어진 값을 반환하고 생성기를 종료합니다.
Generator.prototype.throw()
- 생성기로 에러를 throw합니다.
예시
무한 반복자
function* idMaker(){
var index = 0;
while(true)
yield index++;
}
var gen = idMaker(); // "Generator { }"
console.log(gen.next().value); // 0
console.log(gen.next().value); // 1
console.log(gen.next().value); // 2
// ...
오래된 Generator 객체
Firefox (SpiderMonkey)는 JavaScript 1.7에서 이전 버전의 생성기도 구현 했습니다.이 버전에서는 함수 선언에서 별표 (*)가 필요하지 않습니다 (함수 본문에서 yield
키워드 만 사용). 그러나 오래된 생성기는 더 이상 사용되지 않습니다. 사용하지 마십시오. 곧 제거 될 것입니다 (bug 1083482).
오래된 Generator 메서드들
Generator.prototype.next()
Non-Standardyield
표현을 통해 yield된 값을 반환합니다. ES2015 Generator 객체의next()
에 해당합니다.Generator.prototype.close()
Non-Standard- Generator를 닫고,
next()가 호출되면
StopIteration
에러를 던집니다. ES2015 Generator 객체의return()
에 해당합니다. Generator.prototype.send()
Non-Standard- Generator에 값을 전달하기 위해 사용 합니다. 이 값은
yield
표현식에서 반환되고, 다음yield
표현식으로 부터 yield된 값을 반환합니다.send(x)
는 ES2015 Generator 객체의next(x)에 해당합니다
. Generator.
prototype.
throw()
Non-Standard- Generator 로 에러를 throw합니다. ES2015 Generator 객체의
throw()
에 해당합니다.
오래된 Generator 예제
function* fibonacci() {
var a = yield 1;
yield a * 2;
}
var it = fibonacci();
console.log(it); // "Generator { }"
console.log(it.next()); // 1
console.log(it.send(10)); // 20
console.log(it.close()); // undefined
console.log(it.next()); // throws StopIteration (as the generator is now closed)
명세
Specification |
---|
ECMAScript Language Specification # sec-generator-objects |
브라우저 호환성
BCD tables only load in the browser