Generator function dùng từ khóa yield để sinh giá trị và giữ trạng thái, có thể tiếp tục từ chỗ dừng.
Ví dụ
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Document</title> <style> body { font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif; } .sample { font-size: 18px; font-weight: 500; } </style> </head> <body> <h1>Generator Function trong JavaScript</h1> <div class="sample"></div> <button class="Btn">NHẤN VÀO ĐÂY</button> <h3> Nhấn nút để gọi generator function sinh kết quả </h3> <script> let sampleEle = document.querySelector(".sample"); function* generate(num) { yield 2 * num; yield 3 * num; yield 4 * num; yield 5 * num; } let Gen = generate(8); document.querySelector(".Btn").addEventListener("click", () => { sampleEle.innerHTML += Gen.next().value + "<br>"; sampleEle.innerHTML += Gen.next().value + "<br>"; sampleEle.innerHTML += Gen.next().value + "<br>"; sampleEle.innerHTML += Gen.next().value + "<br>"; }); </script> </body> </html>
Kết quả
Kết quả lần lượt: 16, 24, 32, 40 (tương ứng 2*8, 3*8, 4*8, 5*8).