生成器未定义

时间:2016-01-10 05:38:13

标签: javascript arrays ecmascript-6

我尝试使用此代码测试ES6生成器:

thegenerator instanceof Generator

但是我一直得到ReferenceError: Generator is not defined

这也很奇怪,因为当我把它当作Array

时我得到了这个
TypeError: Object [object Generator] has no method 'indexOf'

3 个答案:

答案 0 :(得分:4)

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

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

FIDDLE

答案 1 :(得分: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/

答案 2 :(得分:2)

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

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