현재 번역은 완벽하지 않습니다. 한국어로 문서 번역에 동참해주세요.

This is a new technology, part of the ECMAScript 2015 (ES6) standard.
This technology's specification has been finalized, but check the compatibility table for usage and implementation status in various browsers.

Generator 객체는 generator function  으로부터 반환된 값이며 반복자와 반복자 프로토콜을 준수합니다.


function* gen() { 
  yield 1;
  yield 2;
  yield 3;

var g = gen(); // "Generator { }"

yield 표현을 통해 yield된 값을 반환합니다.
주어진 값을 반환하고 생성기를 종료합니다.
생성기로 에러를 throw합니다.


무한 반복자

function* idMaker(){
    var index = 0;
        yield index++;

var gen = idMaker(); // "Generator { }"

console.log(; // 0
console.log(; // 1
console.log(; // 2
// ...

오래된 생성기 객체

Firefox (SpiderMonkey) also implements an earlier version of generators in JavaScript 1.7, where the star (*) in the function declaration was not necessary (you just use the yield keyword in the function body). However, legacy generators are deprecated. Do not use them; they are going to be removed (bug 1083482).

오래된 생성기 메서드들
Returns a value yielded by the yield expression. This corresponds to next() in the ES2015 generator object.
Closes the generator, so that when calling next() an StopIteration error will be thrown. This corresponds to the return() method in the ES2015 generator object.
Used to send a value to a generator. The value is returned from the yield expression, and returns a value yielded by the next yield expression. send(x) corresponds to next(x) in the ES2015 generator object.
Throws an error to a generator. This corresponds to the throw() method in the ES2015 generator object.

오래된 생성기 예제

function* fibonacci() {
  var a = yield 1;
  yield a * 2;

var it = fibonacci();
console.log(it);          // "Generator {  }"
console.log(;   // 1
console.log(it.send(10)); // 20
console.log(it.close());  // undefined
console.log(;   // throws StopIteration (as the generator is now closed)


Specification Status Comment
ECMAScript 2015 (6th Edition, ECMA-262)
The definition of 'Generator objects' in that specification.
Standard Initial definition.

브라우저 호환성

Feature Chrome Firefox (Gecko) Internet Explorer Opera Safari
Basic support 39.0 (Yes) No support No support No support
Feature Android Android Webview Firefox Mobile (Gecko) IE Mobile Opera Mobile Safari Mobile Chrome for Android
Basic support No support 39.0 (Yes) No support No support No support 39.0

같이 보기

오래된 생성기

ES2015 생성기

문서 태그 및 공헌자

 이 페이지의 공헌자: kdex, preco21
 최종 변경: kdex,