如何识别ES6发电机

Dan*_*Tao 5 javascript generator ecmascript-harmony

说我有这样的生成器函数:

var g = function*() {
  yield 1;
  yield 2;
  yield 3;
};

var gen = g();
Run Code Online (Sandbox Code Playgroud)

如何以编程方式告诉它g是生成器函数,还是gen迭代器?

这似乎是一种可能性:

g.constructor.name === 'GeneratorFunction'
Run Code Online (Sandbox Code Playgroud)

有没有更好的办法?

更新:我最终采取了类似于Eric的答案的方法,但eval首先使用首先确定目标平台是否支持生成器.这是实施:

var GeneratorConstructor = (function() {
  try {
    var generator;
    return eval('generator = function*() { yield 1; };').constructor;

  } catch (e) {
    // If the above throws a SyntaxError, that means generators aren't
    // supported on the current platform, which means isGenerator should
    // always return false. So we'll return an anonymous function here, so
    // that instanceof checks will always return false.
    return function() {};
  }
}());

/**
 * Checks whether a function is an ES6 Harmony generator.
 *
 * @private
 * @param {Function} fn
 * @returns {boolean}
 */
function isGenerator(fn) {
  return fn instanceof GeneratorConstructor;
}
Run Code Online (Sandbox Code Playgroud)

And*_*ark 5

来自当前 ES6 草案的下图非常有用,可以显示生成器函数和其他对象之间的关系:

图 2(信息性)——生成器对象关系

因此,g instanceof GeneratorFunction如果您有对 的全局引用GeneratorFunction,则看起来您应该可以使用,否则我认为您当前的方法很好。

以下是GeneratorFunctionV8 单元测试文件中获取对其他相关对象的引用的方法:

function* g() { yield 1; }
var GeneratorFunctionPrototype = Object.getPrototypeOf(g);
var GeneratorFunction = GeneratorFunctionPrototype.constructor;
var GeneratorObjectPrototype = GeneratorFunctionPrototype.prototype;
Run Code Online (Sandbox Code Playgroud)


Eri*_*ric 5

将您的解决方案与其他解决方案相结合,可以避免对全局解决方案的需求GeneratorFunction:

g instanceof (function*() {}).constructor
Run Code Online (Sandbox Code Playgroud)