javascript - JavaScript 中的 "function*"是什么?

标签 javascript function ecmascript-6

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 first yield expression, which specifies the value to be returned from the iterator or, with yield*, 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/

相关文章:

javascript - 如何更改所选元素的标签背景? javascript ?或PHP?

javascript - 在非 mozilla 浏览器中应用 MozTransform(通过 JS)

c - 段错误(核心已转储)

javascript - JavaScript 中有多少个参数太多了?

angularjs - 如何在 Sinon JS 的单元测试中处理 sinon.stub().throws()

javascript - 如何将数组转换为新数组

javascript - 如何在 AngularJS 中获取多个复选框的值?

r - 利用 dplyr 中的 across() 内的函数来处理成对列

javascript - 单击时将数组项移动到另一个数组

javascript - 如何从 ES6 类中创建迭代器