检查函数是否是生成器 [英] check if function is a generator

查看:25
本文介绍了检查函数是否是生成器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 Nodejs v0.11.2 中使用了生成器,我想知道我如何检查我的函数的参数是生成器函数.

I played with generators in Nodejs v0.11.2 and I'm wondering how I can check that argument to my function is generator function.

我是这样发现的 typeof f === 'function' &&Object.getPrototypeOf(f) !== Object.getPrototypeOf(Function) 但我不确定这是否是好的(并在未来工作)方式.

I found this way typeof f === 'function' && Object.getPrototypeOf(f) !== Object.getPrototypeOf(Function) but I'm not sure if this is good (and working in future) way.

您对这个问题有何看法?

What is your opinion about this issue?

推荐答案

我们在 TC39 面对面会议中讨论过这个,我们故意不公开检测函数是否为生成器的方法或不.原因是任何函数都可以返回一个可迭代对象,所以不管它是函数还是生成器函数.

We talked about this in the TC39 face-to-face meetings and it is deliberate that we don't expose a way to detect whether a function is a generator or not. The reason is that any function can return an iterable object so it does not matter if it is a function or a generator function.

var iterator = Symbol.iterator;

function notAGenerator() {
  var  count = 0;
  return {
    [iterator]: function() {
      return this;
    },
    next: function() {
      return {value: count++, done: false};
    }
  }
}

function* aGenerator() {
  var count = 0;
  while (true) {
    yield count++;
  }
}

这两个行为相同(减去 .throw() 但也可以添加)

These two behave identical (minus .throw() but that can be added too)

这篇关于检查函数是否是生成器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆