在这个页面中,我发现了一个新的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;
}
}
我已经知道什么是yield, let和[?,?]=[?,?),但不知道函数*是什么意思。是什么?
附注:不要尝试谷歌,它不可能搜索带有星号的表达式(它们被用作占位符)。
功能*
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 first yield expression, which specifies the value to be returned from the iterator or, with yield*, delegates to another generator function. The next() method returns an object with a value property containing the yielded value and a done property which indicates whether the generator has yielded its last value, as a boolean. Calling the next() method with an argument will resume the generator function execution, replacing the yield expression where an execution was paused with the argument from next().
Documentation: MDN
函数*生成器(i) {
产量我;
产量I + 10;
}
Const gen = generator(10);
console.log (gen.next () value);
//期望输出:10
console.log (gen.next () value);
//期望输出:20
它是一个生成器函数。
生成器是可以退出和稍后重新输入的函数。它们的上下文(变量绑定)将在重新进入时保存。
调用生成器函数不会立即执行它的主体;返回函数的迭代器对象。当迭代器的next()方法被调用时,生成器函数的主体将被执行,直到第一个yield表达式(它指定从迭代器返回的值)或使用yield*委托给另一个生成器函数。
历史的注意:
这是EcmaScript.next的建议语法。
Mozilla的Dave Herman做了一个关于EcmaScript.next的演讲。30:15他谈到了发电机。
早些时候,他解释了Mozilla是如何实验性地实现提议的语言变化,以帮助指导委员会。Dave与Brendan Eich密切合作,Brendan Eich是Mozilla的CTO(我认为),也是最初的JavaScript设计者。
您可以在EcmaScript工作组wiki上找到更多细节:http://wiki.ecmascript.org/doku.php?id=harmony:generators
工作组(TC-39)普遍同意EcmaScript。接下来应该有一些生成器迭代器的建议,但这不是最终的。
你不应该指望下一个版本的语言没有变化就会出现这种情况,即使它没有变化,也可能暂时不会在其他浏览器中广泛出现。
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