是否无法确定函数是否是生成器函数(如果已对.bind()进行了调用)? [英] Is it impossible to tell if a function is a generator function if .bind() has been called on it?

查看:106
本文介绍了是否无法确定函数是否是生成器函数(如果已对.bind()进行了调用)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

就像在任何生成器函数上调用.bind(this)一样,破坏了我查看该函数是否是生成器的能力.有关如何解决此问题的任何想法?

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

推荐答案

由于.bind()返回一个新的(存根)函数,该函数仅使用.apply()调用原始函数以附加适当的this值,因此显然不再是您的发电机,而这就是问题的根源.

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.

此节点模块中有一个解决方案: https://www.npmjs.org/package/generator-bind .

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

您可以按原样使用该模块,也可以查看它们如何解决(基本上,它们使.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).

这篇关于是否无法确定函数是否是生成器函数(如果已对.bind()进行了调用)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆