Javascript 未定义生成器

Javascript 未定义生成器,javascript,arrays,ecmascript-6,Javascript,Arrays,Ecmascript 6,我正在尝试使用以下代码测试ES6生成器: thegenerator instanceof Generator 但是,我不断得到ReferenceError:未定义生成器 这也很奇怪,因为当我将它作为数组处理时,我得到了这个 TypeError: Object [object Generator] has no method 'indexOf' 您可以使用constructor.name属性来计算 function isGenerator(name) { return name ===

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

thegenerator instanceof Generator
但是,我不断得到
ReferenceError:未定义生成器

这也很奇怪,因为当我将它作为
数组处理时,我得到了这个

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

您可以使用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'

您只需比较构造函数,因为它是继承的,所以它应该与新生成器相同

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

尝试使用
对象.getPrototypeOf()
.toString()


你能发布一个演示来重现这个问题吗?生成器的类型是函数。@elclanrs我不知道ES6是否可以。但这只是第一行。是的,Chrome和FF本机支持生成器,或者使用Babel尝试JSFIDLE或jsbin。生成器的类型是ObjectI,我对您的代码很感兴趣,所以我运行了它:,但我遇到了一个错误:
Function.prototype.toString不是泛型的
现在是false:/returns[Object]@JSFIDLE
Object.getPrototypeOf(thegenerator.prototype).toString()==“[对象生成器]”
返回
true
,此处位于chromium 49,其中
thegenerator
const thegenerator=function*({})啊,我在
谷歌Chrome:47.0.2526.106(官方版本)
这可能是problem@jasonszhao“当我将其视为数组时获取此值”注意,
Generator
不是一个
Array
值得一提的是为什么它不可用-原因是您不应该关心某个东西是否是一个生成器-而且这些检查很脆弱,会在子类或编译时失败
Object.getPrototypeOf(thegenerator).toString() === "[object Generator]"