Generator

Baseline 已廣泛支援

此特性已非常成熟,可在多種裝置和瀏覽器版本上使用。自 ⁨2016 年 9 月⁩以來,它已在各大瀏覽器中可用。

Generator 物件是由 生成器函式 返回的物件,它同時符合 可迭代協議迭代器協議

Generator 是隱藏的 Iterator 類的子類。

建構函式

沒有 JavaScript 實體與 Generator 建構函式對應。Generator 的例項必須由 生成器函式 返回。

js
function* generator() {
  yield 1;
  yield 2;
  yield 3;
}

const gen = generator(); // "Generator { }"

console.log(gen.next().value); // 1
console.log(gen.next().value); // 2
console.log(gen.next().value); // 3

只有一個隱藏物件,它是所有由生成器函式建立的物件共享的原型物件。該物件通常被風格化為 Generator.prototype 以使其看起來像一個類,但更恰當地稱呼它為 GeneratorFunction.prototype.prototype,因為 GeneratorFunction 是一個實際的 JavaScript 實體。要理解 Generator 例項的原型鏈,請參閱 GeneratorFunction.prototype.prototype

例項屬性

這些屬性定義在 Generator.prototype 上,並被所有 Generator 例項共享。

Generator.prototype.constructor

建立例項物件的建構函式。對於 Generator 例項,初始值為 GeneratorFunction.prototype

注意: Generator 物件不儲存指向建立它們的生成器函式的引用。

Generator.prototype[Symbol.toStringTag]

[Symbol.toStringTag] 屬性的初始值為字串 "Generator"。此屬性用於 Object.prototype.toString()

例項方法

還從其父級 Iterator 繼承例項方法。.

Generator.prototype.next()

返回由 yield 表示式產生的值。

Generator.prototype.return()

作用相當於在生成器當前暫停的位置的體內部插入一個 return 語句,這將結束生成器,並允許生成器在與 try...finally 塊結合使用時執行任何清理任務。

Generator.prototype.throw()

作用相當於在生成器當前暫停的位置的體內部插入一個 throw 語句,它會通知生成器一個錯誤情況,並允許它處理該錯誤,或執行清理並關閉自身。

示例

一個無限迭代器

使用生成器函式,值直到需要時才會被求值。因此,生成器允許我們定義一個潛在的無限資料結構。

js
function* infinite() {
  let index = 0;

  while (true) {
    yield index++;
  }
}

const generator = infinite(); // "Generator { }"

console.log(generator.next().value); // 0
console.log(generator.next().value); // 1
console.log(generator.next().value); // 2
// …

規範

規範
ECMAScript® 2026 語言規範
# sec-generator-objects

瀏覽器相容性

另見