javascript中的生成器

问题描述

function* print() {
  yield console.log("before");
  yield console.log("hello world ");
  return console.log("this is second line ");
}

let o = print();

o.next(); //console.log("before");
o.next(); // console.log("hello world ");
o.next(); //console.log("this is second line ")

为什么当我分配给 o 时可以访问迭代器?如果我单独调用 print().next() ,似乎迭代器会在使用后关闭

解决方法

来自 mozilla.org

function* 声明(function 关键字后跟一个星号)定义了一个生成器函数,它返回一个 Generator 对象。

这意味着,当您将其分配给变量时,该变量将成为该函数的对象。所以当你为它迭代的对象调用 .next() 时。

但是如果直接调用print().next()函数给generator函数,它不会返回任何对象。这看起来类似于您从头开始生成对象并每次调用它的第一个值。