我尝试使用此代码测试ES6生成器:
thegenerator instanceof Generator
但是我一直得到ReferenceError: Generator is not defined
这也很奇怪,因为当我把它当作Array
TypeError: Object [object Generator] has no method 'indexOf'
答案 0 :(得分:4)
答案 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'
答案 2 :(得分:2)
尝试使用Object.getPrototypeOf()
,.toString()
Object.getPrototypeOf(thegenerator).toString() === "[object Generator]"