--- title: Generator slug: Web/JavaScript/Reference/Global_Objects/Generator translation_of: Web/JavaScript/Reference/Global_Objects/Generator ---
Generator
là một object return bởi một {{jsxref("Statements/function*", "generator function", "", 1)}}, nó phù hợp với cả iterable protocol và iterator protocol.
function* gen() { yield 1; yield 2; yield 3; } var g = gen(); // "Generator { }"
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 // ...
Firefox (SpiderMonkey) đã hiện thực phiên bản generators đầu tiên trong JavaScript 1.7, lúc đó dấu sao (*) trong khai báo không bắt buộc (bạn chỉ cần dùng từ khóa yield
bên trong hàm). Tuy nhiên, kiểu viết này đã không còn được hổ trợ từ Firefox 58 (released ngày 23, tháng 1, 2018) ({{bug(1083482)}}).
Generator.prototype.next()
{{non-standard_inline}}next()
in the ES2015 generator object.Generator.prototype.close()
{{non-standard_inline}}next()
an {{jsxref("StopIteration")}} error will be thrown. This corresponds to the return()
method in the ES2015 generator object.Generator.prototype.send()
{{non-standard_inline}}send(x)
corresponds to next(x)
in the ES2015 generator object.Generator.
prototype.
throw()
{{non-standard_inline}}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(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 | Status | Comment |
---|---|---|
{{SpecName('ES2015', '#sec-generator-objects', 'Generator objects')}} | {{Spec2('ES2015')}} | Initial definition. |
{{SpecName('ESDraft', '#sec-generator-objects', 'Generator objects')}} | {{Spec2('ESDraft')}} |
{{Compat("javascript.builtins.Generator")}}