What is “function*” in JavaScript?
在这个页面中,我发现了一个新的javascript函数类型:
1 2 3 4 5 6 7 8 9 10 | // NOTE:"function*" is not supported yet in Firefox. // Remove the asterisk in order for this code to work in Firefox 13 function* fibonacci() { // !!! this is the interesting line !!! let [prev, curr] = [0, 1]; for (;;) { [prev, curr] = [curr, prev + curr]; yield curr; } } |
我已经知道
另外,不要费心去尝试谷歌,搜索带有星号的表达式是不可能的(它们被用作占位符)。
这是一个发生器功能。
Generators are functions which can be exited and later re-entered. Their context (variable bindings) will be saved across re-entrances.
Calling a generator function does not execute its body immediately; an iterator object for the function is returned instead. When the iterator's
next() method is called, the generator function's body is executed until the firstyield expression, which specifies the value to be returned from the iterator or, withyield* , delegates to another generator function.
历史记录:
这是为
Mozilla的Dave Herman做了一个关于ecmascript的演讲。30:15他谈到发电机。
早些时候,他解释了Mozilla是如何实验性地实现所提议的语言变化来帮助指导委员会的。Dave与BrendanEich、Mozilla的CTO(我认为)和最初的JavaScript设计师密切合作。
您可以在ecmascript工作组wiki上找到更多详细信息:http://wiki.ecmascript.org/doku.php?id=和谐:发电机
工作组(TC-39)同意ecmascript.next应该有某种生成器迭代器建议,但这不是最终的建议。
在下一个版本的语言没有改变的情况下,您不应该依赖于这种显示,即使它没有改变,它可能在一段时间内不会在其他浏览器中广泛显示。
Overview
First-class coroutines, represented as objects encapsulating suspended execution contexts (i.e., function activations). Prior art: Python, Icon, Lua, Scheme, Smalltalk.
Examples
The"infinite" sequence of Fibonacci numbers (notwithstanding behavior around 253):
1
2
3
4
5
6
7 function* fibonacci() {
let [prev, curr] = [0, 1];
for (;;) {
[prev, curr] = [curr, prev + curr];
yield curr;
}
}Generators can be iterated over in loops:
1
2
3
4
5
6 for (n of fibonacci()) {
// truncate the sequence at 1000
if (n > 1000)
break;
print(n);
}Generators are iterators:
1
2
3
4
5
6 let seq = fibonacci();
print(seq.next()); // 1
print(seq.next()); // 2
print(seq.next()); // 3
print(seq.next()); // 5
print(seq.next()); // 8
它是一个生成器函数——它在你引用的页面上这么说,在你替换为"这是有趣的一行"的评论中……
基本上,它是一种以编程方式指定序列的方法,这样就可以通过索引传递和访问元素,而不必预先计算整个序列(可能是无限大的)。
从本质上讲,这会将每个值逐个返回给迭代此函数的对象,这就是为什么它们的用例会在foreach样式循环中显示它。