Generator not defined

I am trying to test the ES6 generator using this code:

thegenerator instanceof Generator

However i keep getting ReferenceError: Generator is not defined

It’s also strange because I get it when I consider it as Array

TypeError: Object [object Generator] has no method 'indexOf'
+4
source share
3 answers

You can simply compare the constructor, since it inherited it, it should be the same as the new generator

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

Fiddle

+4
source

You can use the constructor.name property to define.

function isGenerator(name) {
    return name === 'GeneratorFunction';
}

console.log(isGenerator(gen.constructor.name)); // true
console.log(isGenerator(normal.constructor.name)); // false

Otherwise, they are largely 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.net/7gwravha/2/

+2
source

Object.getPrototypeOf(), .toString()

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

Source: https://habr.com/ru/post/1623627/


All Articles