假设我有一个像这样的生成器函数:
var g = function*() {
yield 1;
yield 2;
yield 3;
};
var gen = g();
我如何以编程方式告诉这g
是一个生成器函数,或者gen
一个迭代器?
这似乎是一种可能性:
g.constructor.name === 'GeneratorFunction'
有没有更好的办法?
更新:我最终采用了类似于Eric 的回答的方法,但eval
首先确定目标平台是否支持生成器。这是实现:
var GeneratorConstructor = (function() {
try {
var generator;
return eval('generator = function*() { yield 1; };').constructor;
} catch (e) {
// If the above throws a SyntaxError, that means generators aren't
// supported on the current platform, which means isGenerator should
// always return false. So we'll return an anonymous function here, so
// that instanceof checks will always return false.
return function() {};
}
}());
/**
* Checks whether a function is an ES6 Harmony generator.
*
* @private
* @param {Function} fn
* @returns {boolean}
*/
function isGenerator(fn) {
return fn instanceof GeneratorConstructor;
}