【问题标题】:javascript: How to tell if I'm within a generator function?javascript:如何判断我是否在生成器函数中?
【发布时间】:2017-08-16 04:57:50
【问题描述】:

喂!我在玩function* 和yield。我已经注意到(在 NodeJS 中)无论如何,当我不在 function* 内时尝试调用 yield 时,yield 是未定义的。虽然yield 是关键字,但我无法准确检查yield === undefined。

所以我要问的是,如何判断我的代码当前是否通过function* 运行?

【问题讨论】:

标签: javascript


【解决方案1】:

由于生成器不可构造,您可以尝试使用new GeneratorFunction(),如果它是生成器函数,它会抛出 TypeError。

function* gen() {
  yield 1;
}

function fn() {
  return 1;
}

function isGenerator(fn) {
  try {
    new fn();
    return false;
  } catch (err) {
    return true;
  }
}

console.log(isGenerator(gen)); // true
console.log(isGenerator(fn)); // false

您还可以检查Object.getPrototypeOf(gen),它将返回一个生成器构造函数。然后你可以这样做:

console.log(Object.getPrototypeOf(gen).prototype[Symbol.toStringTag]); // Generator

【讨论】:

    【解决方案2】:

    要了解您当前是否在GeneratorFunction 中,您可以检查函数的构造函数:

    function* generator() {
      
      // Recommended:
      console.log(Object.getPrototypeOf(generator).constructor === Object.getPrototypeOf(function*(){}).constructor);
      
      // Deprecated:
      console.log(Object.getPrototypeOf(arguments.callee).constructor === Object.getPrototypeOf(function*(){}).constructor);
    }
    
    generator().next();

    【讨论】:

      猜你喜欢
      • 2010-09-10
      • 1970-01-01
      • 2019-05-02
      • 2015-01-02
      • 2010-12-30
      • 2014-09-10
      • 2011-08-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多