在 this页面我发现了一个新的 JavaScript 函数类型:
// 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;
}
}
我已经知道了what yield
, let
and [?,?]=[?,?]
do ,但不知道 function*
是什么意思。这是什么?
附:不要费心尝试谷歌,它是 impossible搜索带星号的表达式 (they're used as placeholders)。
最佳答案
这是一个 Generator功能。
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.
历史记录:
这是 EcmaScript.next
的建议语法。
Mozilla 的 Dave Herman 发表了关于 EcmaScript.next 的演讲.在 30:15他谈到了发电机。
早些时候,他解释了 Mozilla 如何通过实验性地实现提议的语言更改来帮助指导委员会。 Dave 与 Mozilla 的 CTO(我认为)和最初的 JavaScript 设计师 Brendan Eich 密切合作。
您可以在 EcmaScript 工作组 wiki 上找到更多详细信息:http://wiki.ecmascript.org/doku.php?id=harmony:generators
工作组 (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):
function* fibonacci() { let [prev, curr] = [0, 1]; for (;;) { [prev, curr] = [curr, prev + curr]; yield curr; } }
Generators can be iterated over in loops:
for (n of fibonacci()) { // truncate the sequence at 1000 if (n > 1000) break; print(n); }
Generators are iterators:
let seq = fibonacci(); print(seq.next()); // 1 print(seq.next()); // 2 print(seq.next()); // 3 print(seq.next()); // 5 print(seq.next()); // 8
关于javascript - JavaScript 中的 "function*"是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9620586/