检查功能是否是发生器 [英] check if function is a generator

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

问题描述

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



I以这种方式发现 typeof f ==='function'&& Object.getPrototypeOf(f)!== Object.getPrototypeOf(Function)但是我不知道这是否很好(并在将来工作)。



你对这个问题有什么看法?

解决方案

我们在TC39面对面谈过这件事会议是故意的,我们不会公开一种检测功能是否是发电机的方法。原因是任何函数都可以返回一个可迭代的对象,所以如果它是一个函数或一个生成函数,这并不重要。

  var iterator = Symbol.iterator; 

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

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

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


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.

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?

解决方案

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++;
  }
}

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

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

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