เรียนรู้ Scope ใน JavaScript และความแตกต่างระหว่าง Global Scope, Local Scope, และ Lexical Scope
Scope หมายถึง context ที่ function หรือ variable เข้าถึงได้ JavaScript มี 3 scope types:
- Global variable: ตัวแปรที่ประกาศนอก code block
- Local variable: ตัวแปรที่ประกาศใน code block
คุ้มค่าที่จะรู้: Functions เข้าถึง variables และ functions ที่อยู่ นอก ตัวเองได้ — แต่เข้าถึง variables ที่อยู่ ใน functions อื่น ไม่ได้
Global Scope
Variable/function ใน global scope เข้าถึงได้จากใน functions อื่น:
// Global scope
let dogBreed = "Labrador";
let getDogBreed = function() {
// dogBreed เข้าถึงได้เพราะอยู่ใน global scope
console.log(dogBreed); // "Labrador"
};
getDogBreed();
รวมถึง functions ใน functions:
// Global scope
let dogBreed = "Labrador";
let getDogBreed = function() {
// function ใน function
let getDogBreedFromGlobalScope = function() {
// เข้าถึง dogBreed จาก global scope
console.log(dogBreed); // "Labrador"
};
getDogBreedFromGlobalScope();
};
getDogBreed();
Local Scope
Variable/function ด้วย local scope เข้าถึงได้แค่จาก context (scope) ของตัวเอง:
let getDogBreed = function() {
// local variable scope
let dogBreed = "Labrador";
// เข้าถึงได้เพราะอยู่ใน local scope
console.log(dogBreed); // "Labrador"
};
ตัวแปร dogBreed มี local scope เข้าถึงได้แค่ใน scope ของมัน (ใน curly braces { .. })
โค้ดเดียวกันแต่ย้าย console.log(dogBreed) นอก local scope (กลายเป็น global scope):
let getDogBreed = function() {
let dogBreed = "Labrador";
};
// ลองเข้าถึง locally scoped variable
console.log(dogBreed); // Uncaught ReferenceError: dogBreed is not defined
Error: "dogBreed is not defined" เพราะพยายาม log locally scoped variable จาก global scope
Lexical Scope
เมื่อ nest functions (วาง function ใน function) variables และ functions ใน parent function (outermost) เข้าถึงได้จาก inner functions — เรียกว่า lexical scope
แต่ parent function เอง เข้าถึง variables/functions ใน inner functions ไม่ได้
// Global scope
let animals = function() {
// Lexical scope
let dogBreed = "Labrador";
// Nested function
let getAnimals = function() {
// เข้าถึง dogBreed ได้เพราะอยู่ใน lexical scope
console.log(dogBreed); // "Labrador"
// Locally scoped variable
let catBreed = "Persian";
console.log(catBreed); // "Persian"
};
getAnimals();
// ทำงานเพราะ dogBreed อยู่ใน lexical scope
console.log(dogBreed); // "Labrador"
// ไม่ทำงาน เพราะ catBreed ไม่อยู่ใน lexical scope เป็น local ของ getAnimals()
console.log(catBreed); // Uncaught ReferenceError: catBreed is not defined
};
animals();