Thuta Learning
JavaScript
AdvancedProgrammingအခြေခံ

Scope & Context

JavaScriptသင်ခန်းစာ 3125 မိနစ်

ဒီခန်းပြီးရင် ဘာတတ်သွားမလဲ

  • Global, module, function နဲ့ block scope လေးမျိုးကို ခွဲခြားပြီး variable တစ်ခု ဘယ်မှာ မြင်ရလဲ ခန့်မှန်းနိုင်ဖို့
  • var က block ကို လျစ်လျူရှုပြီး let/const က block ထဲမှာပဲ နေကြောင်း ရှင်းပြနိုင်ဖို့
  • Scope chain က အတွင်းကနေ အပြင်ကိုပဲ ရှာကြောင်းနဲ့ lexical scope ကို code ရေးထားတဲ့ နေရာက ဆုံးဖြတ်ကြောင်း သိဖို့
  • Shadowing bug တွေကို ရှာတွေ့ပြီး scope (variable တွေ) နဲ့ context (this) ကို ခွဲခြားနိုင်ဖို့

ရိုးရိုးလေး ရှင်းပြမယ်

ရိုးရိုးလေး ရှင်းရရင်

အဆောက်အဦ တစ်လုံးကို စဉ်းစားကြည့်ပါ။ Lobby မှာ ကပ်ထားတဲ့ ကြေညာချက်ကို အခန်းတိုင်းက လူတွေ ဆင်းဖတ်လို့ ရပါတယ်။ အခန်းတစ်ခန်းထဲက whiteboard ပေါ်က စာကိုတော့ အဲဒီအခန်းထဲက လူတွေပဲ မြင်ရပြီး lobby က လူတွေ မမြင်ရပါဘူး။ Scope ဆိုတာ အဲဒီ အခန်းတွေလိုပါပဲ — variable တစ်ခုကို ဘယ်နေရာကနေ ဖတ်လို့ ရလဲ ဆုံးဖြတ်ပေးပါတယ်။

JavaScript မှာ အခန်းတွေက တစ်ခုထဲ တစ်ခု ရှိပါတယ်။ အတွင်းခန်းကနေ အပြင်ခန်းက စာကို မြင်ရပေမယ့် အပြင်ကနေ အတွင်းကို မမြင်ရပါဘူး။ Function တစ်ခုနဲ့ { } block တစ်ခုစီက အခန်းအသစ်တစ်ခုစီပါ။

Problem → Why → Solution

ပြဿနာ: total ကို ပေါင်းထားပေမယ့် 0 ပဲ ကျန်နေတယ်

Shopping cart တစ်ခုရဲ့ စုစုပေါင်းကို တွက်ဖို့ function တစ်ခု ရေးထားပါတယ်။ Function ထဲမှာ ဈေးနှုန်းတွေကို total ထဲ ပေါင်းထည့်နေပေမယ့် function ပြီးလို့ total ကို print ထုတ်ကြည့်တော့ 0 ပဲ ရပါတယ်။ Error မရှိ၊ warning မရှိပါဘူး။ ပြဿနာက let total ဆိုတဲ့ စာလုံး တစ်လုံးတည်းမှာ ရှိပါတယ်။

cart.js
let total = 0;

function addItems(items) {
  let total = 0; // a NEW total that hides the outer one
  for (const item of items) {
    total += item.price;
  }
}

addItems([{ price: 5 }, { price: 7 }]);
console.log(total); // 0 — the outer total never changed

ဘာကြောင့် 0 ဖြစ်နေတာလဲ

Function ထဲက let total က function scope ထဲမှာ variable အသစ်တစ်ခု ဖန်တီးပြီး အပြင်က total ကို ဖုံးကွယ်ထားပါတယ် (shadowing)။ Loop က အတွင်း total ကိုပဲ ပြင်ပြီး function ပြီးတာနဲ့ အဲဒီ variable ပျောက်သွားပါတယ်။ ပိုကောင်းတဲ့ ဖြေရှင်းနည်းက အပြင် variable ကို ပြင်တာ မဟုတ်ဘဲ function ကနေ ရလဒ်ကို return ပြန်ပြီး const total = addItems(items) လို့ ရေးတာပါ။

Core concept: scope လေးမျိုးနဲ့ scope chain

Scope ဆိုတာ identifier (variable, function, class နာမည်) တစ်ခုကို အသုံးပြုလို့ရတဲ့ code ရဲ့ ဧရိယာပါ။ JavaScript မှာ အဓိက scope လေးမျိုး ရှိပါတယ်။ Global scope က အပြင်ဆုံး ဖြစ်ပြီး ဘယ်နေရာကနေမဆို မြင်ရပါတယ်။ Module scope ကတော့ ES module (import/export သုံးတဲ့ ဖိုင်) တစ်ခုစီရဲ့ top level ပါ၊ export မလုပ်ရင် တခြားဖိုင်တွေက မမြင်ရပါဘူး။ Function scope က function ထဲမှာ ကြေညာတဲ့ အရာတွေအတွက်ဖြစ်ပြီး block scope ကတော့ if, for, while နဲ့ { } တို့ရဲ့ ကွင်းအတွင်းပါ။

Keyword က ဘယ် scope ရမလဲ ဆုံးဖြတ်ပါတယ်။ let, const နဲ့ class က block scope ကို လေးစားပြီး ကွင်းပိတ်တာနဲ့ ပျောက်သွားပါတယ်။ var ကတော့ block ကို လျစ်လျူရှုပြီး အနီးဆုံး function (ဒါမှမဟုတ် global) scope ထဲ ရောက်သွားပါတယ်။ ဒါကြောင့် if block ထဲမှာ var နဲ့ ကြေညာထားတာကို block အပြင်ကနေ ဖတ်လို့ ရနေတာပါ။

JavaScript က lexical scope ကို သုံးပါတယ်။ Function တစ်ခုက ဘယ် variable တွေ မြင်ရမလဲဆိုတာ code ကို ရေးထားတဲ့ နေရာ (nesting) က ဆုံးဖြတ်ပြီး ဘယ်ကနေ ခေါ်လဲ ဆိုတာနဲ့ မဆိုင်ပါဘူး။ နာမည်တစ်ခုကို သုံးလိုက်တဲ့အခါ engine က လက်ရှိ scope ကနေ စရှာပြီး မတွေ့ရင် အပြင်တစ်ထပ်ချင်းစီကို global ထိ ဆက်ရှာပါတယ် — ဒါကို scope chain လို့ ခေါ်ပါတယ်။ ဘယ်မှာမှ မတွေ့ရင် ReferenceError တက်ပါတယ်။ ရှာတာ အပြင်ကိုပဲ သွားပြီး အတွင်းကို ဘယ်တော့မှ မဆင်းပါဘူး။

အတွင်း scope မှာ အပြင်က နာမည်နဲ့ တူတဲ့ variable တစ်ခု ကြေညာရင် ရှာတာ အတွင်းမှာပဲ ရပ်သွားလို့ အပြင် variable ကို ဖုံးကွယ်ပါတယ် (shadowing)။ ဒါက တရားဝင်ပေမယ့် problem section မှာ မြင်ခဲ့သလို ရှုပ်ထွေးစေပါတယ်။ ဖိုင်တိုင်း၊ function တိုင်းက ပြင်နိုင်တဲ့ global variable တွေကလည်း code အစိတ်အပိုင်းတွေကို ချိတ်ဆက်မိစေပြီး test တစ်ခုက ပြောင်းလိုက်တဲ့ value က နောက် test ကို ထိခိုက်စေပါတယ်။ Parameter တွေနဲ့ module export တွေက dependency တွေကို မျက်မြင် ဖြစ်စေပါတယ်။

text
Looking up a name walks the scope chain outward
-----------------------------------------------
+-- global / module scope ------------------------------+
|  globalVar                                            |
|  +-- function outer() -------------------------------+ |
|  |  outerVar                                         | |
|  |  +-- function inner() ---------------------------+ | |
|  |  |  innerVar                                     | | |
|  |  |  uses outerVar:  inner -> outer (found)       | | |
|  |  +-----------------------------------------------+ | |
|  +---------------------------------------------------+ |
+-------------------------------------------------------+
မှတ်ထားရမယ့် ပုံစံ: အတွင်းကနေ အပြင်ကို ရှာတယ်
  1. လက်ရှိ block / function ထဲမှာ အရင်ရှာ
  2. မတွေ့ရင် အပြင်တစ်ထပ် တက်ရှာ
  3. Global ထိ ဆက်ရှာ၊ မတွေ့ရင် ReferenceError
  4. ပထမဆုံး တွေ့တဲ့ နာမည်က အနိုင်ရ (shadowing)

အပြင်ကို ကြည့်လို့ရပေမယ့် အတွင်းကို ဘယ်တော့မှ ငုံ့ကြည့်လို့ မရပါဘူး။

အထွေထွေ ပုံစံ

javascript
const shared = value;          // module/global scope

function name(param) {         // function scope: param, local
  const local = value;
  if (condition) {             // block scope
    const temp = value;        // gone after the closing brace
    var leaked = value;        // var escapes to function scope
  }
  return local;                // shared, param, local, leaked visible
}

Scope တစ်ထပ်စီကို ကွင်းတွေနဲ့ မြင်ကြည့်ပါ။ အတွင်းဆုံး block က အပြင်က အရာအားလုံးကို မြင်ရပေမယ့် temp ကို block အပြင်ကနေ မမြင်ရပါဘူး။ var က block ကို ဖြတ်ပြီး function scope ထဲ ရောက်သွားပါတယ်။

Example: global, function, block နဲ့ lexical scope

ဒီ example က scope တစ်ထပ်စီကနေ variable တွေကို ဖတ်ကြည့်ပါတယ်။ Scope အပြင်က နာမည်ကို တိုက်ရိုက် ဖတ်ရင် ReferenceError တက်ပြီး script ရပ်သွားမှာမို့ အဲဒီ နာမည်တွေကို typeof နဲ့ ဘေးကင်းကင်း စစ်ထားပါတယ်၊ ဒါကြောင့် run ကြည့်ရင် ရလဒ်အားလုံးကို ကိုယ်တိုင် မြင်ရပါမယ်။ typeof က မကြေညာထားတဲ့ နာမည်အတွက် error မတက်ဘဲ "undefined" ပြန်ပါတယ်။

scope.js
// Global (top-level) scope
let globalVar = "I'm global";

function demoScope() {
  // Function scope
  var functionVar = "I'm in function";

  if (true) {
    // Block scope
    let blockVar = "I'm in block";
    var notBlock = "I'm function scoped"; // var ignores the block

    console.log(globalVar);   // OK: outer scope
    console.log(functionVar); // OK: enclosing function
    console.log(blockVar);    // OK: same block
  }

  console.log(functionVar);   // OK
  console.log(notBlock);      // OK: var escaped the if-block
  console.log(typeof blockVar); // "undefined": blockVar is gone
}

demoScope();
console.log(globalVar);          // OK
console.log(typeof functionVar); // "undefined": function scope is private

// Lexical scope: inner functions see outer variables
function outer() {
  let outerVar = "outer";

  function inner() {
    let innerVar = "inner";
    console.log(`${outerVar} + ${innerVar}`);
  }

  inner();
}
outer();

Code ကို တစ်ပိုင်းချင်း ရှင်းပြမယ်

  1. Line 2let globalVar = "I'm global";

    Top level မှာ ကြေညာထားလို့ ဖိုင်ထဲက ဘယ် function ကမဆို ဖတ်လို့ရပါတယ်။ Script ဖြစ်ရင် global scope၊ ES module ဖြစ်ရင် module scope ထဲ ရောက်ပါတယ်။

  2. Lines 10-11var notBlock = "I'm function scoped"; // var ignores the block

    blockVar (let) က if block ထဲမှာပဲ ရှိပေမယ့် notBlock (var) ကတော့ block ကို လျစ်လျူရှုပြီး demoScope ရဲ့ function scope ထဲ ရောက်သွားပါတယ်။

  3. Line 19console.log(notBlock); // OK: var escaped the if-block

    Block ပိတ်ပြီးသွားပေမယ့် notBlock ကို ဖတ်လို့ ရနေဆဲပါ။ var ရဲ့ ဒီ အပြုအမူက loop counter တွေ block အပြင်ကို ယိုစိမ့်ထွက်တဲ့ bug တွေရဲ့ အရင်းအမြစ်ပါ။

  4. Line 20console.log(typeof blockVar); // "undefined": blockVar is gone

    blockVar ကို if block ပြင်ပမှာ မမြင်ရတော့ပါဘူး။ console.log(blockVar) လို့ တိုက်ရိုက် ရေးရင် ReferenceError တက်ပါမယ်၊ typeof ကတော့ "undefined" လို့ပဲ ပြပါတယ်။

  5. Line 33console.log(`${outerVar} + ${innerVar}`);

    inner() ထဲမှာ outerVar မရှိလို့ engine က scope chain အတိုင်း outer() ဆီ တက်ရှာပြီး တွေ့ပါတယ်။ inner ကို outer ထဲမှာ ရေးထားလို့ပဲ ဒီလို မြင်ရတာပါ (lexical scope)။

You should see
I'm global
I'm in function
I'm in block
I'm in function
I'm function scoped
undefined
I'm global
undefined
outer + inner

Scope နဲ့ context (this) မတူပါဘူး

ဒီ lesson ရဲ့ ခေါင်းစဉ်မှာ "context" ပါပါတယ်၊ ဒါကြောင့် ခွဲခြားထားဖို့ အရေးကြီးပါတယ်။ Scope က variable နာမည်တွေကို ဘယ်မှာ ရှာမလဲ ဆုံးဖြတ်ပြီး code ရေးတဲ့အချိန်မှာ သတ်မှတ်ပြီးသားပါ။ Context (this) ကတော့ function ကို ဘယ်လို ခေါ်လဲ (ဘယ် object ရဲ့ method အဖြစ် ခေါ်လဲ) ပေါ်မှာ မူတည်ပြီး run တဲ့အချိန်ကျမှ ဆုံးဖြတ်ပါတယ်။ အောက်က code မှာ function တစ်ခုတည်းကို object နှစ်ခုကနေ ခေါ်တော့ this.label ပြောင်းသွားပေမယ့် scope ကနေ ဖတ်တဲ့ label ကတော့ မပြောင်းပါဘူး။

scope-vs-this.js
const label = "module scope";

const box = {
  label: "box property",
  viaThis() {
    return this.label; // context: decided by the call
  },
  viaScope() {
    return label; // scope: decided by where the code is written
  },
};

const other = { label: "other object", viaThis: box.viaThis };

console.log(box.viaThis());   // box property
console.log(other.viaThis()); // other object
console.log(box.viaScope());  // module scope

လက်တွေ့ project တွေမှာ

Real project တွေမှာ ဘယ်လို သုံးလဲ

ယနေ့ JavaScript project အများစုက ES module တွေနဲ့ ရေးကြပါတယ်။ ဖိုင်တစ်ခုစီက ကိုယ်ပိုင် module scope ရှိလို့ ဖိုင်နှစ်ခုမှာ နာမည်တူ helper function ရှိနေလည်း မတိုက်ပါဘူး၊ တခြားဖိုင်က သုံးစေချင်တာကိုပဲ export လုပ်ပါတယ်။ Module system မပေါ်ခင်က script tag တွေ အများကြီးက global scope တစ်ခုတည်းကို မျှသုံးခဲ့ကြလို့ library နှစ်ခု "$" ဆိုတဲ့ နာမည်ကို လုကြတာလို ပြဿနာတွေ ဖြစ်ခဲ့ပါတယ်။

Configuration ကို global variable အဖြစ် ထားမယ့်အစား function parameter အဖြစ် ထည့်ပေးတာ (dependency injection) က test ရေးရ လွယ်စေပါတယ် — test တစ်ခုစီက ကိုယ့် config ကို ပေးလို့ရပြီး တစ်ခုနဲ့တစ်ခု မထိခိုက်ပါဘူး။ Loop တစ်ကြိမ်ချင်းစီအတွက်ပဲ လိုတဲ့ value တွေကို block ထဲမှာ const နဲ့ ကြေညာထားရင် အပြင်ကို မယိုစိမ့်ပါဘူး။ ESLint ရဲ့ no-shadow rule က problem section မှာ မြင်ခဲ့တဲ့ shadowing ကို သတိပေးပြီး TypeScript/ESLint က မကြေညာထားတဲ့ variable သုံးတာကိုလည်း ဖမ်းပေးပါတယ်။

အမှားများ

အဖြစ်များတဲ့ အမှားတွေ

1. မရည်ရွယ်ဘဲ shadowing လုပ်မိတာ

အပြင် variable ကို ပြင်ချင်တာဖြစ်ပေမယ့် function ထဲမှာ let/const ထပ်ရေးမိရင် variable အသစ်တစ်ခု ဖြစ်သွားပြီး အပြင်ကဟာ မပြောင်းပါဘူး။ Assignment ပဲ လိုရင် keyword မထည့်ပါနဲ့၊ ပိုကောင်းတာက ရလဒ်ကို return ပြန်ပါ။

2. ကြေညာမထားတဲ့ variable ကို assign လုပ်တာ

Sloppy mode script တစ်ခုမှာ count = 1; လို့ let/const မပါဘဲ ရေးရင် JavaScript က global variable အသစ်ကို တိတ်တဆိတ် ဖန်တီးပါတယ်။ ES module တွေနဲ့ "use strict" ပါတဲ့ code မှာတော့ ReferenceError တက်ပါတယ်။ Variable တိုင်းကို အမြဲ ကြေညာပါ။

3. Block ထဲက var က ယိုစိမ့်ထွက်တာ

for (var i = 0; i < 3; i++) {} ပြီးရင် i က loop အပြင်မှာ 3 အဖြစ် ကျန်နေပြီး နောက်ပိုင်း code မှာ နာမည်တူ variable နဲ့ ရောနိုင်ပါတယ်။ let သုံးရင် i က loop ထဲမှာပဲ ရှိပါတယ်။

Best Practices

အကောင်းဆုံး အလေ့အကျင့်များ

  • Variable တစ်ခုကို လိုအပ်တဲ့ အသေးဆုံး scope ထဲမှာ ကြေညာပါ။
  • Function တွေကို global value တွေ ဖတ်ခိုင်းမယ့်အစား parameter နဲ့ ထည့်ပေးပြီး ရလဒ်ကို return ပြန်ခိုင်းပါ။
  • Nested scope တွေမှာ နာမည်တူ variable တွေ ပြန်မသုံးပါနဲ့၊ ESLint no-shadow ကို ဖွင့်ထားပါ။

Mini challenge

Mini challenge: global မသုံးတဲ့ order summary

Order list နဲ့ config object ကို parameter အဖြစ် လက်ခံပြီး summary string ပြန်ပေးတဲ့ summarize() ကို ရေးပါ။ Global mutable state မသုံးရပါဘူး၊ ယာယီ value တွေကို block scope ထဲမှာပဲ ထားရပါမယ်။

  • config ({ taxRate, currency }) ကို global ကနေ မဖတ်ဘဲ parameter အဖြစ် လက်ခံရမယ်
  • Order တစ်ခုစီရဲ့ lineTotal ကို loop block ထဲမှာ const နဲ့ ကြေညာရမယ်
  • Tax ကို ဒသမ နှစ်နေရာ round လုပ်ပြီး "items=2 subtotal=20.00 USD tax=2.00 USD" ပုံစံ string ကို return ပြန်ရမယ်
  • Config နှစ်မျိုးနဲ့ ခေါ်ပြီး lineTotal က အပြင်ကို မယိုစိမ့်ကြောင်း typeof နဲ့ ပြရမယ်
summary.js
function summarize(orders, config) {
  // TODO: read taxRate and currency from config (not from a global)
  // TODO: let subtotal = 0
  // TODO: loop over orders; declare lineTotal with const inside the loop
  // TODO: round the tax to 2 decimals
  // TODO: return "items=N subtotal=X.XX CUR tax=Y.YY CUR"
}

// TODO: print summarize(...) for a USD config with taxRate 0.1
// TODO: print summarize(...) for a EUR config with taxRate 0.05
// TODO: print typeof lineTotal

ရလဒ်: Config တစ်ခုစီအတွက် summary တစ်ကြောင်းစီနဲ့ နောက်ဆုံးမှာ undefined ထွက်ရပါမယ်: items=2 subtotal=20.00 USD tax=2.00 USD items=1 subtotal=30.00 EUR tax=1.50 EUR undefined

အရိပ်အမြွက် ကြည့်ရန်

Parameter ထဲမှာ destructuring သုံးပြီး function summarize(orders, { taxRate, currency }) လို့ ရေးလို့ ရပါတယ်။ Math.round(x * 100) / 100 နဲ့ round လုပ်ပြီး toFixed(2) နဲ့ ပြပါ။

အဖြေ ကြည့်ရန်
summary.js
function summarize(orders, { taxRate, currency }) {
  let subtotal = 0;
  for (const order of orders) {
    const lineTotal = order.qty * order.price; // lives for one iteration
    subtotal += lineTotal;
  }
  const tax = Math.round(subtotal * taxRate * 100) / 100;
  return (
    `items=${orders.length} subtotal=${subtotal.toFixed(2)} ${currency} ` +
    `tax=${tax.toFixed(2)} ${currency}`
  );
}

const usd = { taxRate: 0.1, currency: "USD" };
const eur = { taxRate: 0.05, currency: "EUR" };

console.log(summarize([{ qty: 2, price: 4.5 }, { qty: 1, price: 11 }], usd));
console.log(summarize([{ qty: 3, price: 10 }], eur));
console.log(typeof lineTotal);

Quick Quiz 1 / 3

if (true) { var a = 1; let b = 2; } console.log(typeof a, typeof b); က ဘာ print ထုတ်မလဲ။

Quick Quiz 2 / 3

let total = 0; function add(n) { let total = n; } add(5); console.log(total); ရဲ့ output က ဘာလဲ။

Quick Quiz 3 / 3

const name = "global"; function printName() { console.log(name); } function run() { const name = "local"; printName(); } run(); က ဘာ print ထုတ်မလဲ။

မှတ်ထားရမယ့် အချက်များ

  • Scope က variable တစ်ခုကို ဘယ်မှာ မြင်ရလဲ ဆုံးဖြတ်ပြီး global, module, function, block ဆိုပြီး လေးမျိုး ရှိပါတယ်။
  • let/const/class က block scope ကို လေးစားပြီး var က block ကို ဖြတ်ကာ function scope ထဲ ရောက်ပါတယ်။
  • Scope chain က အတွင်းကနေ အပြင်ကိုပဲ ရှာပြီး lexical scope ကို code ရေးထားတဲ့ နေရာက ဆုံးဖြတ်ပါတယ်။
  • Shadowing နဲ့ global mutable state ကို ရှောင်ပါ၊ scope (variable) နဲ့ context (this) ကို မရောပါနဲ့။

MDN — JavaScript Guide — MDN Web Docs

နောက်ဆုံးပြင်ဆင်ရက်

Progress ကို ဤ browser (ဤစက်) တွင်သာ သိမ်းထားပါသည်။ အခြားစက်များနှင့် sync မလုပ်ပါ။

ဤသင်ခန်းစာတွင် အမှားတွေ့ပါက အကြောင်းကြားရန်သင့် email app ကို ဤသင်ခန်းစာလိပ်စာ ဖြည့်ပြီးသားဖြင့် ဖွင့်ပေးပါမည် — သင်ကိုယ်တိုင် ပို့မှသာ ပို့မည်ဖြစ်သည်။