function*关键字可以在表达式内部定义一个生成器函数。
function* [name]([param1[, param2[, ..., paramN]]]) {
statements
}
nameparamNstatementsfunction*表达式和function* 声明比较相似,并具有几乎相同的语法。function*表达式和function*声明之间主要区别就是函数名,即在创建匿名函数时,function*表达式可以省略函数名。阅读函数章节了解更多信息。
下面的示例定义了一个未命名的生成器函数并把它赋值给x。函数产出它的传入参数的平方:
var x = function*(y) {
yield y * y;
};
| Specification | Status | Comment |
|---|---|---|
| ECMAScript 2015 (6th Edition, ECMA-262) function* |
Standard | Initial definition. |
| ECMAScript Latest Draft (ECMA-262) function* |
Draft |
| Desktop | Mobile | Server | ||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
function* | Chrome Full support Yes | Edge Full support Yes | Firefox Full support 26 | IE No support No | Opera Full support Yes | Safari Full support 10 | WebView Android Full support Yes | Chrome Android Full support Yes | Edge Mobile Full support Yes | Firefox Android Full support 26 | Opera Android Full support Yes | Safari iOS Full support 10 | Samsung Internet Android Full support Yes | nodejs Full support Yes |
| Trailing comma in parameters | Chrome Full support 58 | Edge ? | Firefox Full support 52 | IE No support No | Opera Full support 45 | Safari ? | WebView Android Full support 58 | Chrome Android Full support 58 | Edge Mobile ? | Firefox Android Full support 52 | Opera Android Full support 45 | Safari iOS ? | Samsung Internet Android Full support 7.0 | nodejs Full support 8.0.0 |