It is not possible to determine if a function is a generator function if .bind () is called on it?

It seems that calling .bind (this) on any generator function violates my ability to see if this 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 
+5
javascript generator ecmascript-harmony
Nov 06 '14 at 0:11
source share
3 answers

Since .bind() returns a new (stub) function that only calls the original with .apply() to attach the correct this value, this is obviously not your generator anymore, and this is the source of your problem.

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

You can use this module as is or see how they solve it (basically they make a new function returned by .bind() , also a generator).

+6
Nov 06 '14 at 0:14
source share

Yes, you can determine if a function is a generator, even if .bind () was called on it:

 function testIsGen(f) { return Object.getPrototypeOf(f) === Object.getPrototypeOf(function*() {}); } 
+1
May 01 '16 at
source share

This package has a solution:

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

Basically, to make it work, you need to either polyfill Function.prototype.bind, or call your own bind () method.

0
Nov 06 '14 at 2:42
source share



All Articles