admin管理员组文章数量:1410697
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]"
本文标签: javascriptGenerator is not definedStack Overflow
版权声明:本文标题:javascript - Generator is not defined - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744270597a2598164.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论