javascript `return function *(){...}` 是什么意思?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19833945/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What does `return function *(){...}` mean?
提问by Afshin Mehrabani
I saw something strange in Koa. It has some new function names (from https://github.com/koajs/koa/blob/master/examples/co.js#L10):
我在Koa看到了一些奇怪的东西。它有一些新的函数名称(来自https://github.com/koajs/koa/blob/master/examples/co.js#L10):
app.use(function(){
return function *(){
var paths = yield fs.readdir('docs');
var files = yield paths.map(function(path){
return fs.readFile('docs/' + path, 'utf8');
});
this.type = 'markdown';
this.body = files.join('');
}
});
What does return function *()
mean? Can we declare a function with the name of *
in JavaScript?
什么return function *()
意思?我们可以*
在 JavaScript 中声明一个名为 的函数吗?
采纳答案by benjaminbenben
It means that the function returns an iterator (so it can be repeatedly called with .next() to yield more values.
这意味着该函数返回一个迭代器(因此可以使用 .next() 重复调用它以产生更多值。
check out http://wingolog.org/archives/2013/05/08/generators-in-v8for more info
查看http://wingolog.org/archives/2013/05/08/generators-in-v8了解更多信息
It's an ES6 construct, so at the moment you see it more in node rather than client side js
它是一个 ES6 结构,所以目前你更多地在节点而不是客户端 js 中看到它
回答by Luc Morin
Koa makes use of a new JavaScript feature called generators, and the *
is the way to identify a generator in V8.
Koa 使用了一个名为generators的新 JavaScript 特性,这*
是在 V8 中识别生成器的方法。