Kir*_*met 5 javascript generator node.js ecmascript-harmony
看起来在任何生成器函数上调用.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
Run Code Online (Sandbox Code Playgroud)
由于.bind()返回一个新的(存根)函数,只是.apply()为了附加正确的this值而只调用原始函数,它显然不再是您的生成器,这是您的问题的根源.
此节点模块中有一个解决方案:https://www.npmjs.org/package/generator-bind.
您可以按原样使用该模块,也可以查看它们是如何解决的(基本上它们会使.bind()返回的新函数也成为生成器).
| 归档时间: |
|
| 查看次数: |
1571 次 |
| 最近记录: |