I'm trying to test for an ES6 generator with this code:
thegenerator instanceof Generator
However I keep getting ReferenceError: Generator is not defined
It's also weird because I get this when I treat it as an Array
TypeError: Object [object Generator] has no method 'indexOf'
I'm trying to test for an ES6 generator with this code:
thegenerator instanceof Generator
However I keep getting ReferenceError: Generator is not defined
It's also weird because I get this when I treat it as an Array
TypeError: Object [object Generator] has no method 'indexOf'
Share
Improve this question
edited Jan 10, 2016 at 5:46
asked Jan 10, 2016 at 5:38
user2486953user2486953
10
- Can you post a demo to reproduce the problem? – elclanrs Commented Jan 10, 2016 at 5:39
- Type of generators are function. – Ahmet Cetin Commented Jan 10, 2016 at 5:44
- @elclanrs I don't know if that's possible with ES6. But it's just that first one liner. – user2486953 Commented Jan 10, 2016 at 5:47
- Yes, Chrome and FF support generators natively, or try jsfiddle or jsbin with Babel. – elclanrs Commented Jan 10, 2016 at 5:50
- Generators are of type Object – adeneo Commented Jan 10, 2016 at 5:51
3 Answers
Reset to default 4You can just pare the constructor, as it's inherited it should be the same as a new generator
thegenerator.constructor === (function*(){}()).constructor;
FIDDLE
You can use the constructor.name property to figure out.
function isGenerator(name) {
return name === 'GeneratorFunction';
}
console.log(isGenerator(gen.constructor.name)); // true
console.log(isGenerator(normal.constructor.name)); // false
Otherwise they are pretty much indistinguishable.
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/7gwravha/2/
Try using Object.getPrototypeOf()
, .toString()
Object.getPrototypeOf(thegenerator).toString() === "[object Generator]"