---
title: Generator
slug: Web/JavaScript/Reference/Global_Objects/Generator
translation_of: Web/JavaScript/Reference/Global_Objects/Generator
---
<div>{{JSRef}}</div>

<p>O objeto <code><strong>Generator</strong></code> é retornado por {{jsxref("Statements/function*", "generator function", "", 1)}} e conforme <a href="/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#iterable">iterable protocol</a> e o <a href="/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#iterator">iterator protocol</a>.</p>

<h2 id="Síntaxe">Síntaxe</h2>

<pre class="syntaxbox">function* gen() {
  yield 1;
  yield 2;
  yield 3;
}

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

<h2 id="Métodos">Métodos</h2>

<dl>
 <dt>{{jsxref("Generator.prototype.next()")}}</dt>
 <dd>Retorna o valor fornecido pela expressão {{jsxref("Operators/yield", "yield")}}.</dd>
 <dt>{{jsxref("Generator.prototype.return()")}}</dt>
 <dd>Retorna o valor fornecido a finaliza o generator.</dd>
 <dt>{{jsxref("Generator.prototype.throw()")}}</dt>
 <dd>Lança um erro no generator.</dd>
</dl>

<h2 id="Example">Example</h2>

<h3 id="An_infinite_iterator">An infinite iterator</h3>

<pre class="brush: js">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
// ...</pre>

<h2 id="Objeto_legacy_generator">Objeto legacy generator</h2>

<p>Firefox (SpiderMonkey) também implementa a versão anterior do generator em <a href="/en-US/docs/Web/JavaScript/New_in_JavaScript/1.7">JavaScript 1.7</a>, onde o asterisco (*) na declaração da função não era necessário (somente era necessário usar a palavra reservada <code>yield</code> no corpo da função). Contudo, legacy generators estão obsoletos. Não os use, eles serão removidos ({{bug(1083482)}}).</p>

<h3 id="Métodos_legacy_generator">Métodos legacy generator</h3>

<dl>
 <dt><code>Generator.prototype.next() </code>{{non-standard_inline}}</dt>
 <dd>Retorna o valor fornecido pela expressão {{jsxref("Operators/yield", "yield")}}. Isto corresponde ao <code>next() </code>do ES6.</dd>
 <dt><code>Generator.prototype.close()</code> {{non-standard_inline}}</dt>
 <dd>Fecha o generator, então quando chamar <code>next()</code> um erro {{jsxref("StopIteration")}}  será lançado. Isto corresponde ao  método <code>return()</code> do ES6.</dd>
 <dt><code>Generator.prototype.send()</code> {{non-standard_inline}}</dt>
 <dd>Usado para enviar um valor para o generator. Este valor é retordo pela expressão {{jsxref("Operators/yield", "yield")}}, e retorna o valor fornecido pelo pelo next {{jsxref("Operators/yield", "yield")}}. <code>send(x)</code> corresponde ao <code>next(x)</code> do ES6.</dd>
 <dt><strong><code>Generator.</code></strong><code>prototype.</code><strong><code>throw()</code> </strong> {{non-standard_inline}}</dt>
 <dd>Lança um erro no generator. Isto corresponde ao método <code>throw() do ES6.</code></dd>
</dl>

<h3 id="Exemplo_do_Legacy_generator">Exemplo do Legacy generator</h3>

<pre class="brush: js">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 (Como o generator está fechado)
</pre>

<h2 id="Especificações">Especificações</h2>

<table class="standard-table">
 <tbody>
  <tr>
   <th scope="col">Especificações</th>
   <th scope="col">Status</th>
   <th scope="col">Comentário</th>
  </tr>
  <tr>
   <td>{{SpecName('ES6', '#sec-generator-objects', 'Generator objects')}}</td>
   <td>{{Spec2('ES6')}}</td>
   <td>Definição Inicial</td>
  </tr>
  <tr>
   <td>{{SpecName('ESDraft', '#sec-generator-objects', 'Generator objects')}}</td>
   <td>{{Spec2('ESDraft')}}</td>
   <td> </td>
  </tr>
 </tbody>
</table>

<h2 id="Browser_compatibility">Compatibilidade com navegadores</h2>

<p>{{CompatibilityTable}}</p>

<div id="compat-desktop">
<table class="compat-table">
 <tbody>
  <tr>
   <th>Feature</th>
   <th>Chrome</th>
   <th>Firefox (Gecko)</th>
   <th>Internet Explorer</th>
   <th>Opera</th>
   <th>Safari</th>
  </tr>
  <tr>
   <td>Basic support</td>
   <td>{{CompatChrome(39.0)}}</td>
   <td>{{CompatVersionUnknown}}</td>
   <td>{{CompatNo}}</td>
   <td>{{CompatNo}}</td>
   <td>{{CompatNo}}</td>
  </tr>
 </tbody>
</table>
</div>

<div id="compat-mobile">
<table class="compat-table">
 <tbody>
  <tr>
   <th>Feature</th>
   <th>Android</th>
   <th>Android Webview</th>
   <th>Firefox Mobile (Gecko)</th>
   <th>IE Mobile</th>
   <th>Opera Mobile</th>
   <th>Safari Mobile</th>
   <th>Chrome for Android</th>
  </tr>
  <tr>
   <td>Basic support</td>
   <td>{{CompatNo}}</td>
   <td>{{CompatChrome(39.0)}}</td>
   <td>{{CompatVersionUnknown}}</td>
   <td>{{CompatNo}}</td>
   <td>{{CompatNo}}</td>
   <td>{{CompatNo}}</td>
   <td>{{CompatChrome(39.0)}}</td>
  </tr>
 </tbody>
</table>
</div>

<h2 id="Veja_Também">Veja Também</h2>

<h3 id="Legacy_generators">Legacy generators</h3>

<ul>
 <li>{{jsxref("Statements/Legacy_generator_function", "The legacy generator function", "", 1)}}</li>
 <li>{{jsxref("Operators/Legacy_generator_function", "The legacy generator function expression", "", 1)}}</li>
 <li>{{jsxref("StopIteration")}}</li>
 <li><a href="/en-US/docs/Web/JavaScript/Reference/Deprecated_and_obsolete_features/The_legacy_Iterator_protocol">The legacy Iterator protocol</a></li>
</ul>

<h3 id="ES6_generators">ES6 generators</h3>

<ul>
 <li>{{jsxref("Functions", "Functions", "", 1)}}</li>
 <li>{{jsxref("Statements/function", "function")}}</li>
 <li>{{jsxref("Operators/function", "function expression")}}</li>
 <li>{{jsxref("Function")}}</li>
 <li>{{jsxref("Statements/function*", "function*")}}</li>
 <li>{{jsxref("Operators/function*", "function* expression")}}</li>
 <li>{{jsxref("GeneratorFunction")}}</li>
 <li><a href="/en-US/docs/Web/JavaScript/Guide/The_Iterator_protocol">The Iterator protocol</a></li>
</ul>