如果一个函数是一个生成器函数,如果.bind()已经被调用,是不可能的?
看起来像调用.bind(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
值,显然不再是你的生成器,这是你的问题的根源。
在这个节点模块中有一个解决scheme: https : //www.npmjs.org/package/generator-bind 。
你可以按原样使用这个模块,或者看看它们是如何解决的(基本上它们使得.bind()
返回的新函数也是一个生成器)。
是的,即使调用了.bind(),也可以判断函数是否为生成器:
function testIsGen(f) { return Object.getPrototypeOf(f) === Object.getPrototypeOf(function*() {}); }
这个软件包有解决scheme:
https://www.npmjs.org/package/generator-bind
基本上,为了得到它的工作,你要么polyfill Function.prototype.bind或调用一个自定义的bind()方法。