Is it impossible to tell if a function is a generator function if .bind() has been called on it?

二次信任 提交于 2019-12-23 11:00:19

问题


Looks like calling .bind(this) on any generator function breaks my ability to see if the function is a generator. Any ideas on how to fix this?

var isGenerator = function(fn) {
    if(!fn) {
        return false;
    }

    var isGenerator = false;

    // Faster method first
    // Calling .bind(this) causes fn.constructor.name to be 'Function'
    if(fn.constructor.name === 'GeneratorFunction') {
        isGenerator = true;
    }
    // Slower method second
    // Calling .bind(this) causes this test to fail
    else if(/^function\s*\*/.test(fn.toString())) {
        isGenerator = true;
    }

    return isGenerator;
}

var myGenerator = function*() {
}

var myBoundGenerator = myGenerator.bind(this);

isGenerator(myBoundGenerator); // false, should be true

回答1:


Since .bind() returns a new (stub) function that only just calls the original with .apply() in order to attach the proper this value, it is obviously no longer your generator and that is the source of your issue.

There is a solution in this node module: https://www.npmjs.org/package/generator-bind.

You can either use that module as is or see how they solve it (basically they make the new function that .bind() returns also be a generator).




回答2:


Yes, it is possible to tell if a function is a generator even if .bind() has been called on it:

function testIsGen(f) {
  return Object.getPrototypeOf(f) === Object.getPrototypeOf(function*() {});
}



回答3:


This package has the solution:

https://www.npmjs.org/package/generator-bind

Basically, in order to get it to work you either need to polyfill Function.prototype.bind or call a custom bind() method.



来源:https://stackoverflow.com/questions/26769593/is-it-impossible-to-tell-if-a-function-is-a-generator-function-if-bind-has-be

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!