check if function is a generator

后端 未结 12 1418
-上瘾入骨i
-上瘾入骨i 2020-11-29 06:03

I played with generators in Nodejs v0.11.2 and I\'m wondering how I can check that argument to my function is generator function.

I found this way typeof f ===

12条回答
  •  猫巷女王i
    2020-11-29 06:23

    In node 7 you can instanceof against the constructors to detect both generator functions and async functions:

    const GeneratorFunction = function*(){}.constructor;
    const AsyncFunction = async function(){}.constructor;
    
    function norm(){}
    function*gen(){}
    async function as(){}
    
    norm instanceof Function;              // true
    norm instanceof GeneratorFunction;     // false
    norm instanceof AsyncFunction;         // false
    
    gen instanceof Function;               // true
    gen instanceof GeneratorFunction;      // true
    gen instanceof AsyncFunction;          // false
    
    as instanceof Function;                // true
    as instanceof GeneratorFunction;       // false
    as instanceof AsyncFunction;           // true
    

    This works for all circumstances in my tests. A comment above says it doesn't work for named generator function expressions but I'm unable to reproduce:

    const genExprName=function*name(){};
    genExprName instanceof GeneratorFunction;            // true
    (function*name2(){}) instanceof GeneratorFunction;   // true
    

    The only problem is the .constructor property of instances can be changed. If someone was really determined to cause you problems they could break it:

    // Bad people doing bad things
    const genProto = function*(){}.constructor.prototype;
    Object.defineProperty(genProto,'constructor',{value:Boolean});
    
    // .. sometime later, we have no access to GeneratorFunction
    const GeneratorFunction = function*(){}.constructor;
    GeneratorFunction;                     // [Function: Boolean]
    function*gen(){}
    gen instanceof GeneratorFunction;      // false
    

提交回复
热议问题