การประกาศฟังก์ชัน* ใช้เพื่อกำหนดฟังก์ชันตัวสร้าง ส่งคืนวัตถุตัวสร้าง ฟังก์ชันตัวสร้างช่วยให้สามารถเรียกใช้โค้ดได้ในระหว่างที่ออกจากฟังก์ชันและกลับมาทำงานต่อในภายหลัง ดังนั้น เครื่องกำเนิดไฟฟ้าสามารถใช้เพื่อจัดการการควบคุมการไหลในโค้ดได้
ไวยากรณ์
นี่คือไวยากรณ์ −
function *myFunction() {}
// or
function* myFunction() {}
// or
function*myFunction() {} มาดูวิธีใช้ฟังก์ชันตัวสร้างกัน
ตัวอย่าง
สาธิตสด
<html>
<body>
<script>
function* display() {
var num = 1;
while (num < 5)
yield num++;
}
var myGenerator = display();
document.write(myGenerator.next().value);
document.write("<br>"+myGenerator.next().value);
document.write("<br>"+myGenerator.next().value);
document.write("<br>"+myGenerator.next().value);
document.write("<br>"+myGenerator.next().value);
</script>
</body>
</html>