【问题标题】:Generator is not defined生成器未定义
【发布时间】:2016-01-10 05:38:12
【问题描述】:

我正在尝试使用以下代码测试 ES6 生成器:

thegenerator instanceof Generator

但是我不断收到ReferenceError: Generator is not defined

这也很奇怪,因为当我将其视为 Array 时,我得到了这个

TypeError: Object [object Generator] has no method 'indexOf'

【问题讨论】:

  • 你能发布一个演示来重现这个问题吗?
  • 生成器的类型是函数。
  • @elclanrs 我不知道 ES6 是否有可能。但这只是第一个班轮。
  • 是的,Chrome 和 FF 原生支持生成器,或者尝试使用 Babel 的 jsfiddle 或 jsbin。
  • 生成器的类型为 Object

标签: javascript arrays ecmascript-6


【解决方案1】:

你可以只比较构造函数,因为它是继承的,它应该和一个新的生成器一样

thegenerator.constructor === (function*(){}()).constructor;

FIDDLE

【讨论】:

  • 值得一提的是为什么它不可用 - 原因是你不应该关心某个东西是否是生成器 - 这些检查很脆弱并且会因子类或子类而失败在编译时
【解决方案2】:

你可以使用constructor.name属性来判断。

function isGenerator(name) {
    return name === 'GeneratorFunction';
}

console.log(isGenerator(gen.constructor.name)); // true
console.log(isGenerator(normal.constructor.name)); // false

否则它们几乎无法区分。

const gen = function*() {};
const normal = function() {};

console.log(gen.constructor); // GeneratorFunction()
console.log(typeof gen); // function
console.log(gen instanceof Function); // true
console.log(gen instanceof Object); // true

console.log(normal.constructor); // Function()
console.log(typeof normal); // function
console.log(normal instanceof Function); // true
console.log(normal instanceof Object); // true

console.log(gen.constructor.name); // 'GeneratorFunction'
console.log(normal.constructor.name); // 'Function'

https://jsfiddle.net/7gwravha/2/

【讨论】:

    【解决方案3】:

    尝试使用Object.getPrototypeOf().toString()

    Object.getPrototypeOf(thegenerator).toString() === "[object Generator]"
    

    【讨论】:

    • 我对你的代码很感兴趣,所以我运行了它:jsfiddle.net/36dc4n8j,但我收到了一个错误:Function.prototype.toString is not generic
    • 现在是假的:/返回[Object object]
    • @AR7 在 jsfiddle jsfiddle.net/36dc4n8j/1 Object.getPrototypeOf(thegenerator.prototype).toString() === "[object Generator]" 返回 true ,这里是 chromium 49 ,其中 thegeneratorconst thegenerator = function*() {};
    • 啊,我在Google Chrome: 47.0.2526.106 (Official Build),这可能是问题
    • @jasonszhao "当我把它当作一个数组时得到这个" 注意,Generator 不是Array
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-02-21
    • 2021-03-25
    • 2013-12-02
    • 2012-12-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多