假设我有一个像这样的发电机功能:
var g = function*() {
yield 1;
yield 2;
yield 3;
};
var gen = g();我如何以编程方式告诉您g是一个生成器函数,还是gen是一个迭代器?
这似乎是一种可能性:
g.constructor.name === 'GeneratorFunction'有更好的办法吗?
Update:我最终得到了类似于埃里克的回答的采取一种方法,但首先使用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;
}发布于 2014-02-04 17:50:04
将您的解决方案与其他解决方案相结合,可以避免对全局GeneratorFunction的需求。
g instanceof (function*() {}).constructor发布于 2014-02-04 17:46:03
来自当前ES6草案的以下图像对于显示生成器函数和其他对象之间的关系非常有用:

因此,如果您有一个对g instanceof GeneratorFunction的全局引用,那么您应该能够使用GeneratorFunction,否则我认为您当前的方法很好。
下面是如何获得从GeneratorFunction借来的对V8单元测试文件和其他相关对象的引用
function* g() { yield 1; }
var GeneratorFunctionPrototype = Object.getPrototypeOf(g);
var GeneratorFunction = GeneratorFunctionPrototype.constructor;
var GeneratorObjectPrototype = GeneratorFunctionPrototype.prototype;发布于 2016-11-11 11:23:37
要判断某物是否是生成器:
const g = (function*() {yield 1;});
const GeneratorFunctionPrototype = Object.getPrototypeOf(g);
function isGenerator(thing) {
return typeof thing === 'object' && thing.constructor === GeneratorFunctionPrototype;
}在最初的问题中,这回答了isGenerator(gen) true。而g是一个生成器函数。当您调用生成器函数时,您将生成一个生成器。
但在大多数情况下,更重要的是要问这件事是否是一个迭代器
function isIterator(thing) {
// If thing has a Symbol.iterator
return typeof thing === 'object' && thing[Symbol.iterator];
}用法:
function *Pseq(list, repeats=1) {
for (let i = 0; i < repeats; i++) {
for (let value of list) {
if (isIterator(value)) {
yield *value;
} else {
yield value;
}
}
}
}
let q = Pseq([1, 2, 3, Pseq([10, 20, 30], 2), 4], 2);
for (let v of q) {
console.log(v);
}1 2 3 10 20 30 10 20 30 4 1 2 3
这是对一个序列的迭代。如果在该序列中嵌入了一个迭代器,那么在继续该序列之前,使用产委托来迭代该序列。生成器并不是唯一能产生有用迭代器的东西。
https://stackoverflow.com/questions/21559365
复制相似问题