Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> JavaScript

วิธีประกาศฟังก์ชันภายในฟังก์ชัน (Nested Functions) ใน JavaScript

เพื่อให้บรรลุเป้าหมายนี้ ใช้ JavaScript Closures Closure คือฟังก์ชันที่ใช้ scope ที่มันถูกประกาศเมื่อถูก invoke ไม่ใช่ scope ที่มันถูก invoke

ตัวอย่าง

var myFunction = (function() { 
  function display() { 
    // 5 
  }; 
  function innerDisplay(a) { 
    if (/* some condition */) { 
      // 1, 2
      display(); 
    } else { 
      // 3, 4
      display(); 
    } 
  } 
  return innerDisplay; 
})();

Closure คืออะไร?

Closure = ฟังก์ชัน + lexical environment (scope) ที่มันถูกสร้างขึ้น ฟังก์ชันภายใน (inner) เข้าถึงตัวแปรของฟังก์ชันภายนอก (outer) ได้ แม้ outer function จบการทำงานแล้ว

ตัวอย่าง Closure จริง

function createCounter() {
  let count = 0;  // private variable
  
  return function() {  // inner function = closure
    count++;
    return count;
  };
}

const counter1 = createCounter();
console.log(counter1());  // 1
console.log(counter1());  // 2

const counter2 = createCounter();
console.log(counter2());  // 1 (แยก scope กัน)

Use Cases ของ Closure

  • Data encapsulation / private variables
  • Function factories (สร้างฟังก์ชันด้วย config ต่างกัน)
  • Callbacks, event handlers ที่ต้องจดจำ state
  • Module pattern