ฟังก์ชันตัวสร้างใช้คีย์เวิร์ดของผลตอบแทนเพื่อสร้างผลลัพธ์และคงสถานะไว้แม้จะกลับมาแล้วก็ตาม ดังนั้นในครั้งถัดไปที่เรียกฟังก์ชันนี้ ฟังก์ชันดังกล่าวจะกลับมาทำงานต่อได้ทันทีจากการรันผลตอบแทนครั้งล่าสุด การเรียกใช้ฟังก์ชันตัวสร้างแต่ละครั้งจะส่งค่ากลับไปยังผู้โทร
ต่อไปนี้เป็นรหัสสำหรับฟังก์ชันตัวสร้างใน JavaScript -
ตัวอย่าง
<!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>JavaScript Generator</h1>
<div class="sample"></div>
<button class="Btn">CLICK HERE</button>
<h3>
Click on the above buttons to call the generator function to generate some result
</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> เอาท์พุต

เมื่อคลิกปุ่ม 'คลิกที่นี่' -
