You’re reading the English version of this content since no translation exists yet for this locale. Help us translate this article!
Khai báo function*
(từ khóa function
tiếp theo là dấu sao) định nghĩa một generator function, một phương thức trả về đối tượng Generator
.
The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
Bạn cũng có thể khai báo generator functions bằng constructor GeneratorFunction
, hoặc cú pháp function expression.
Cú pháp
function* name([param[, param[, ... param]]]) { statements }
name
- Tên phương thức
param
- Các tham số truyền vào cho phương thức.
statements
- Các câu lệnh bên trong phương thức
Diễn giải
Generators là một hàm có thể thoát và sau đó gọi lại lần nữa. Giá trị của biến trong các lần gọi được lưu lại trong các lần gọi tiếp theo.
Pattern là cách hàm async
được viết ra.
Gọi một generator function không thực thi các lệnh bên trong hàm ngày lập tức; Thay vào đó, một object iterator được trả về. Khi iterator gọi đến phương thức next()
, lúc này các lệnh bên trong hàm được thực thi cho đến khi gặp câu yield
, sau câu lệnh yield
là giá trị sẽ trả về, hoặc gọi đến một generator function khác. Phương thức next()
trả về một object với property value
chứa giá trị yielded và property done
, giá trị kiểu boolean, xác định generator yielded trả về đã là cuối cùng chưa. Gọi phương thức next()
với một tham số sẽ chạy hàm generator tiếp tục, thay thế câu yield
nơi hàm đã dừng lại trước đó với tham số từ next()
.
Câu lệnh return
trong generator, khi chạy, sẽ kết thúc generator (ví dụ property done
trả về sẽ có giá trị true
). Nếu giá trị đã được trả về, nó sẽ được set cho property value
.
Giống như câu lệnh return
, thrown error trong generator sẽ kết thúc generator -- trừ khi bắt lại bằng bên trong generator.
Khi một generator kết thúc, các câu gọi next
tiếp theo sau sẽ không được thực thi, nó chỉ trả về object có dạng: {value: undefined, done: true}
.
Ví dụ
Ví dụ đơn giản
function* idMaker() { var index = 0; while (index < index+1) yield index++; } var gen = idMaker(); console.log(gen.next().value); // 0 console.log(gen.next().value); // 1 console.log(gen.next().value); // 2 console.log(gen.next().value); // 3 // ...
Ví dụ với yield*
function* anotherGenerator(i) { yield i + 1; yield i + 2; yield i + 3; } function* generator(i) { yield i; yield* anotherGenerator(i); yield i + 10; } var gen = generator(10); console.log(gen.next().value); // 10 console.log(gen.next().value); // 11 console.log(gen.next().value); // 12 console.log(gen.next().value); // 13 console.log(gen.next().value); // 20
Truyền tham số vào trong Generators
function* logGenerator() { console.log(0); console.log(1, yield); console.log(2, yield); console.log(3, yield); } var gen = logGenerator(); gen.next(); // 0 gen.next('pretzel'); // 1 pretzel gen.next('california'); // 2 california gen.next('mayonnaise'); // 3 mayonnaise
Return bên trong generator
function* yieldAndReturn() { yield "Y"; return "R"; yield "unreachable"; } var gen = yieldAndReturn() console.log(gen.next()); // { value: "Y", done: false } console.log(gen.next()); // { value: "R", done: true } console.log(gen.next()); // { value: undefined, done: true }
Generators không dùng constructable
function* f() {} var obj = new f; // throws "TypeError: f is not a constructor
Generator khai báo bằng expression
const foo = function* () { yield 10; yield 20; }; const bar = foo(); console.log(bar.next()); // {value: 10, done: false}
Specifications
Specification | Status | Comment |
---|---|---|
ECMAScript 2015 (6th Edition, ECMA-262) The definition of 'function*' in that specification. |
Standard | Initial definition. |
ECMAScript 2016 (ECMA-262) The definition of 'function*' in that specification. |
Standard | Changed that generators should not have [[Construct]] trap and will throw when used with new . |
ECMAScript Latest Draft (ECMA-262) The definition of 'function*' in that specification. |
Draft |
Trình duyệt hổ trợ
Desktop | Mobile | Server | |||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
function* | Chrome Full support 39 | Edge Full support 13 | Firefox Full support 26 | IE No support No | Opera Full support 26 | Safari Full support 10 | WebView Android Full support Yes | Chrome Android Full support 39 | Firefox Android Full support 26 | Opera Android Full support Yes | Safari iOS Full support 10 | Samsung Internet Android Full support 4.0 | nodejs
Full support
4.0.0
|
IteratorResult object instead of throwing | Chrome Full support 49 | Edge Full support 13 | Firefox Full support 29 | IE No support No | Opera Full support Yes | Safari Full support Yes | WebView Android Full support Yes | Chrome Android Full support 49 | Firefox Android Full support 29 | Opera Android Full support Yes | Safari iOS Full support Yes | Samsung Internet Android Full support Yes | nodejs Full support Yes |
Not constructable with new (ES2016) | Chrome Full support 50 | Edge Full support 13 | Firefox Full support 43 | IE No support No | Opera Full support 37 | Safari Full support 10 | WebView Android Full support 50 | Chrome Android Full support 50 | Firefox Android Full support 43 | Opera Android Full support 37 | Safari iOS Full support 10 | Samsung Internet Android Full support 5.0 | nodejs Full support Yes |
Trailing comma in parameters | Chrome Full support 58 | Edge Full support 14 | Firefox Full support 52 | IE No support No | Opera Full support 45 | Safari ? | WebView Android Full support 58 | Chrome Android Full support 58 | Firefox Android Full support 52 | Opera Android Full support 43 | Safari iOS ? | Samsung Internet Android Full support 7.0 | nodejs Full support 8.0.0 |
Legend
- Full support
- Full support
- No support
- No support
- Compatibility unknown
- Compatibility unknown
- User must explicitly enable this feature.
- User must explicitly enable this feature.
Firefox-specific notes
Generators and iterators in Firefox versions before 26
Older Firefox versions implement an older version of the generators proposal. In the older version, generators were defined using a regular function
keyword (without an asterisk) among other differences. See Legacy generator function for further information.
IteratorResult
object returned instead of throwing
Starting with Gecko 29 (Firefox 29 / Thunderbird 29 / SeaMonkey 2.26), the completed generator function no longer throws a TypeError
"generator has already finished". Instead, it returns an IteratorResult
object like { value: undefined, done: true }
(bug 958951).
Xem thêm
function* expression
GeneratorFunction
object- Iteration protocols
yield
yield*
Function
objectfunction declaration
function expression
Functions and function scope
- Other web resources: