Scope & Closures
Scope & Closures
Section titled “Scope & Closures”Scope คืออะไร?
Section titled “Scope คืออะไร?”Scope กำหนดว่าตัวแปรจะ มองเห็นและเข้าถึงได้จากตรงไหนใน code
// Global scopeconst globalVar = "ทุกที่เห็น";
function example() { // Function scope const funcVar = "เห็นเฉพาะใน function";
if (true) { // Block scope const blockVar = "เห็นเฉพาะใน block {}"; let alsoBlock = "let ก็ block-scoped"; var notBlock = "var เป็น function-scoped!"; }
console.log(notBlock); // ✅ var หลุด block // console.log(blockVar); // ❌ ReferenceError}# Python ใช้ LEGB rule (Local, Enclosing, Global, Built-in)x = "global"def outer(): x = "enclosing" def inner(): x = "local"// C ใช้ block scope เหมือน let/constint global = 10;void func() { int local = 20; { int block = 30; } // block ใช้ไม่ได้ที่นี่}-- SQL ตัวแปรมี scope ภายใน batch/procedureDECLARE @x INT = 10;-- ใช้ได้ตลอด batchScope Chain
Section titled “Scope Chain”JavaScript ค้นหาตัวแปรจากใน → นอก:
const color = "แดง"; // global
function outer() { const size = "ใหญ่"; // outer scope
function inner() { const shape = "วงกลม"; // inner scope
// inner เห็นทุกตัว console.log(color, size, shape); // "แดง", "ใหญ่", "วงกลม" }
inner(); // console.log(shape); // ❌ ReferenceError}Closures
Section titled “Closures”Closure เกิดเมื่อ function จำ scope ที่มันถูกสร้าง แม้จะถูกเรียกจากที่อื่น:
function createCounter(start = 0) { let count = start; // ตัวแปรนี้ถูก "ปิด" ไว้ใน closure
return { increment: () => ++count, decrement: () => --count, getCount: () => count, };}
const counter = createCounter(10);console.log(counter.increment()); // 11console.log(counter.increment()); // 12console.log(counter.getCount()); // 12// count เข้าถึงตรง ๆ ไม่ได้ — เป็น private!ตัวอย่าง Closure ที่พบบ่อย
Section titled “ตัวอย่าง Closure ที่พบบ่อย”// สร้าง function ที่จำ multiplierfunction multiplier(factor) { return (number) => number * factor;}
const double = multiplier(2);const triple = multiplier(3);
console.log(double(5)); // 10console.log(triple(5)); // 15IIFE (Immediately Invoked Function Expression)
Section titled “IIFE (Immediately Invoked Function Expression)”// IIFE — ประกาศแล้วเรียกทันทีconst result = (function() { const secret = "hidden"; return secret.toUpperCase();})();
console.log(result); // "HIDDEN"// console.log(secret); // ❌ ReferenceError
// Arrow IIFEconst config = (() => { const env = "production"; return { env, debug: env !== "production" };})();