Thuta Learning
JavaScript
AdvancedProgrammingအခြေခံ

Arrow Functions

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

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

  • Function expression တစ်ခုကို parameter အရေအတွက်အလိုက် arrow syntax ပုံစံမှန်နဲ့ ပြောင်းရေးနိုင်ဖို့
  • Concise body (implicit return) နဲ့ block body (return လိုတဲ့ပုံစံ) ကို ခွဲခြားပြီး object literal ကို ကွင်းနဲ့ ပြန်ပေးနိုင်ဖို့
  • Arrow callback က method ရဲ့ this ကို ဘာကြောင့် ဆက်မြင်နေလဲ ရှင်းပြနိုင်ဖို့
  • Object method၊ constructor နဲ့ arguments လိုတဲ့နေရာတွေမှာ ရိုးရိုး function ကို ဘာကြောင့် ရွေးသင့်လဲ ဆုံးဖြတ်နိုင်ဖို့

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

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

JavaScript code ထဲမှာ function သေးသေးလေးတွေကို အမြဲတမ်း ရေးနေရပါတယ်။ Array ထဲက number တိုင်းကို နှစ်ဆလုပ်ဖို့၊ button နှိပ်တဲ့အခါ တစ်ခုခုလုပ်ဖို့ စသဖြင့်ပါ။ function keyword၊ ကွင်းကြီးနဲ့ return ကို အကြိမ်တိုင်း ရေးနေရတာ စာများပြီး အဓိကအလုပ်ကို ဖုံးသွားစေပါတယ်။

Arrow function က ဒီ function သေးလေးတွေကို စာကြောင်းတစ်ကြောင်းတည်းနဲ့ ရေးခွင့်ပေးပါတယ်။ (n) => n * 2 ကို "n ကိုယူပြီး n * 2 ကို ပြန်ပေး" လို့ ဖတ်ရပါတယ်။ ပုံစံတိုရုံတင် မကပါဘူး၊ ကွာခြားချက် အရေးကြီးတစ်ခုလည်း ရှိပါတယ်။ Arrow function မှာ ကိုယ်ပိုင် this မရှိပါဘူး။ ဒါကြောင့် အပြင်ဘက် code ရဲ့ this ကိုပဲ ဆက်သုံးပါတယ်။

Problem → Why → Solution

ပြဿနာ: callback ထဲမှာ this ပျောက်သွားတာ

counter object ရဲ့ start() method ထဲမှာ forEach ကို ရိုးရိုး function callback နဲ့ ခေါ်ထားပါတယ်။ ရေးသူက callback ထဲက this ဟာ counter ကို ညွှန်းနေမယ်လို့ ထင်ထားပါတယ်။ တကယ်တမ်းမှာ forEach က callback ကို ရိုးရိုး function call အနေနဲ့ ခေါ်လို့ this က counter မဟုတ်တော့ပါဘူး။ Module ဒါမှမဟုတ် strict mode file မှာ this က undefined ဖြစ်ပြီး TypeError တက်ပါတယ်။ Script အဟောင်းပုံစံမှာဆိုရင် global object ပေါ်က count ကို NaN လို့ အသံမထွက်ဘဲ ရေးသွားပါတယ်။

ဒုတိယ bug က ပိုလျှို့ဝှက်ပါတယ်။ map ထဲမှာ object ပြန်ပေးချင်လို့ x => { value: x } လို့ ရေးလိုက်ပေမယ့် ရလဒ်က [undefined, undefined] ပဲ ထွက်ပါတယ်။ Error လည်း မပြပါဘူး။

counter.js
const counter = {
  count: 0,
  start() {
    [1, 2, 3].forEach(function () {
      this.count += 1; // TypeError: Cannot read properties of undefined
    });
  },
};
counter.start();

const items = [1, 2].map((x) => { value: x });
console.log(items); // [ undefined, undefined ]

ဘာကြောင့် ဒီလိုဖြစ်တာလဲ

ရိုးရိုး function တိုင်းက ခေါ်တဲ့ပုံစံပေါ်မူတည်ပြီး ကိုယ်ပိုင် this ကို ရပါတယ်။ forEach ထဲက callback ကို object.method() ပုံစံနဲ့ ခေါ်တာမဟုတ်လို့ counter ကို မသိပါဘူး။ ဒုတိယ bug မှာတော့ arrow နောက်က { ကို JavaScript က object မဟုတ်ဘဲ function body ရဲ့ အစလို့ ဖတ်ပါတယ်။ value: ဆိုတာ label တစ်ခုဖြစ်သွားပြီး return မရှိလို့ undefined ပြန်လာတာပါ။

Core concept: arrow function ရဲ့ ပုံစံနဲ့ စည်းမျဉ်းများ

Arrow function ဟာ function expression တစ်မျိုးပါ။ ဒါကြောင့် ပုံမှန်အားဖြင့် const ထဲကို assign လုပ်ပြီး သုံးပါတယ်၊ ဒါမှမဟုတ် map၊ filter၊ setTimeout လို function တွေထဲကို argument အဖြစ် တိုက်ရိုက် ထည့်ပေးပါတယ်။ ရေးပုံကို အပိုင်းနှစ်ပိုင်း ခွဲကြည့်ရအောင်။ => ရဲ့ ဘယ်ဘက်က parameter တွေ၊ ညာဘက်က body ပါ။

၁။ Parameter တွေ

Parameter မရှိရင် () => ... လို့ ကွင်းအလွတ် ရေးရပါတယ်။ Parameter တစ်ခုတည်းဆိုရင် x => ... လို့ ကွင်းမပါဘဲ ရေးလို့ရပေမယ့် team အများစုက (x) => ... လို့ ကွင်းအမြဲထည့်ပါတယ်။ နှစ်ခုနဲ့အထက်၊ default value ဒါမှမဟုတ် destructuring ပါရင်တော့ ကွင်း မဖြစ်မနေ လိုပါတယ်။

၂။ Concise body နဲ့ block body

=> နောက်မှာ expression တစ်ခုတည်း ရေးရင် (concise body) အဲဒီ value ကို return မရေးဘဲ အလိုလို ပြန်ပေးပါတယ်။ { } ကွင်းကြီးနဲ့ statement အများကြီး ရေးရင် (block body) ရိုးရိုး function လိုပဲ return ကို ကိုယ်တိုင် ရေးရပါတယ်။ မရေးရင် undefined ပြန်လာပါတယ်။

၃။ Object literal ကို ကွင်းနဲ့ အုပ်ပါ

=> နောက်က { ကို JavaScript က block body လို့ အမြဲ ယူဆပါတယ်။ Object ကို ပြန်ပေးချင်ရင် (name) => ({ name }) လို့ ကွင်းထဲ ထည့်ရပါတယ်။ ကွင်းက "ဒါ expression ပါ" လို့ parser ကို ပြောပေးတာပါ။

၄။ this၊ arguments ကို ပတ်ဝန်းကျင်ကနေ ယူတယ်

Arrow function မှာ ကိုယ်ပိုင် this၊ arguments နဲ့ super မရှိပါဘူး။ ဒါကို lexical this လို့ ခေါ်ပါတယ်၊ code ကို ရေးထားတဲ့နေရာက this ကို ယူတာပါ။ Method ထဲက callback အတွက် အရမ်းအဆင်ပြေပေမယ့် arrow ကိုယ်တိုင်ကို method အဖြစ် သုံးရင်တော့ object ကို မမြင်ရပါဘူး။

ရိုးရိုး functionArrow function
thisခေါ်ပုံပေါ် မူတည်တယ်ရေးထားတဲ့နေရာကနေ ယူတယ်
new နဲ့ ခေါ်ရင်Object အသစ် ဆောက်ပေးတယ်TypeError: ... is not a constructor
argumentsကိုယ်ပိုင် arguments ရှိတယ်မရှိပါ၊ ...rest ကို သုံးပါ
HoistingDeclaration ဆိုရင် မကြေညာခင် ခေါ်လို့ရconst ဖြစ်လို့ ကြေညာပြီးမှ ခေါ်ရ
Mental model: this ကို အပြင်ကနေ ငှားသုံးတဲ့ function
  1. Parameter တွေကို => ဘယ်ဘက်မှာ ရေး
  2. Expression တစ်ခုဆို အလိုလို return
  3. { } ဖွင့်ရင် return ကို ကိုယ်တိုင်ရေး
  4. this ကို အပြင်ဘက် scope ကနေ ယူ

"ဒီ function ကို ဘယ်သူခေါ်မလဲ" လို့ မမေးပါနဲ့။ Arrow function အတွက် "ဒီ code ကို ဘယ်နေရာမှာ ရေးထားလဲ" ဆိုတာကပဲ this ကို ဆုံးဖြတ်ပါတယ်။

အခြေခံ ပုံစံ

javascript
const noParams = () => expression;
const oneParam = (param) => expression;
const manyParams = (a, b = defaultValue) => expression;

const withBlock = (param) => {
  // several statements
  return result;
};

const makeObject = (key) => ({ key: key });

Expression တစ်ခုတည်းဆိုရင် return မလိုပါဘူး။ { } ဖွင့်တာနဲ့ return ကို ရေးရပါတယ်။ Object ပြန်ပေးချင်ရင်တော့ ({ ... }) ဆိုပြီး ကွင်းနဲ့ အုပ်ပါ။

Arrow function ရဲ့ ပုံစံလေးမျိုးကို run ကြည့်မယ်

အောက်က file မှာ အပိုင်းလေးပိုင်း ပါပါတယ်။ ပထမပိုင်းက function တစ်ခုတည်းကို syntax နှစ်မျိုးနဲ့ ရေးပြတာပါ။ ဒုတိယပိုင်းက concise body နဲ့ block body ကို နှိုင်းယှဉ်ပြတာ၊ တတိယပိုင်းက object literal ပြန်ပေးတာ၊ စတုတ္ထပိုင်းကတော့ method ထဲက arrow callback က this ကို ဘယ်လို ဆက်သုံးလဲ ပြတာပါ။ Run မလုပ်ခင် output လေးကြောင်းကို ကြိုခန့်မှန်းကြည့်ပါ။

arrow-functions.js
// 1. The same function in two syntaxes
const addOld = function (a, b) {
  return a + b;
};
const add = (a, b) => a + b;
console.log(addOld(2, 3), add(2, 3));

// 2. Concise body (implicit return) vs block body (explicit return)
const square = (n) => n * n;
const describe = (n) => {
  const kind = n % 2 === 0 ? "even" : "odd";
  return `${n} is ${kind}`;
};
console.log(square(4), describe(7));

// 3. Returning an object literal needs parentheses
const toItem = (name) => ({ name, done: false });
console.log(["milk", "eggs"].map(toItem));

// 4. An arrow callback uses `this` from the surrounding method
const timer = {
  seconds: 0,
  tickThreeTimes() {
    [1, 2, 3].forEach(() => {
      this.seconds += 1; // `this` is still timer
    });
    return this.seconds;
  },
};
console.log(timer.tickThreeTimes());

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

  1. Same job, shorter syntaxconst add = (a, b) => a + b;

    function keyword၊ { } နဲ့ return ကို ဖြုတ်လိုက်ပေမယ့် addOld နဲ့ အလုပ်တူတူ လုပ်ပါတယ်။ ဒါကြောင့် ပထမ line မှာ 5 5 ထွက်ပါတယ်။

  2. Block body needs returnreturn `${n} is ${kind}`;

    describe မှာ statement နှစ်ကြောင်း လိုလို့ { } ဖွင့်ထားပါတယ်။ ဒါကြောင့် return ကို ကိုယ်တိုင် ရေးရပါတယ်။ ဒီ line ကို ဖျက်လိုက်ရင် describe(7) က undefined ဖြစ်သွားပါမယ်။

  3. Object literal in parenthesesconst toItem = (name) => ({ name, done: false });

    ကွင်းကြောင့် { name, done: false } ကို object အဖြစ် ဖတ်ပါတယ်။ map(toItem) က string တစ်ခုစီကို object တစ်ခုစီ ပြောင်းပေးပါတယ်။

  4. Lexical this in a callbackthis.seconds += 1; // `this` is still timer

    Callback က arrow ဖြစ်လို့ ကိုယ်ပိုင် this မရှိဘဲ tickThreeTimes() ရဲ့ this (timer) ကို သုံးပါတယ်။ ဒါကြောင့် seconds က 3 အထိ တိုးပါတယ်။

  5. The method itself is not an arrowtickThreeTimes() {

    Method ကို shorthand ရိုးရိုး method syntax နဲ့ ရေးထားပါတယ်။ timer.tickThreeTimes() လို့ ခေါ်တဲ့အခါ this က timer ဖြစ်ပြီး အထဲက arrow တွေက အဲဒီ this ကို ငှားသုံးပါတယ်။

You should see
5 5
16 7 is odd
[ { name: 'milk', done: false }, { name: 'eggs', done: false } ]
3

Arrow ကို မသုံးသင့်တဲ့ နေရာများ

Arrow function က ပိုတိုလို့ နေရာတိုင်းမှာ သုံးချင်စိတ် ပေါ်လာတတ်ပါတယ်။ ဒါပေမဲ့ this ကို အပြင်ကနေ ယူတဲ့ အင်္ဂါရပ်ကပဲ နေရာအချို့မှာ ပြဿနာ ဖြစ်စေပါတယ်။ Object method ကို arrow နဲ့ရေးရင် this က object မဟုတ်ဘဲ object ကို ရေးထားတဲ့ ပတ်ဝန်းကျင်ရဲ့ this ဖြစ်သွားပါတယ်။ Constructor အဖြစ် new နဲ့ ခေါ်ရင် TypeError တက်ပြီး prototype property လည်း မရှိပါဘူး။

DOM event listener မှာ this ကို click ခံရတဲ့ element အဖြစ် သုံးချင်ရင်လည်း arrow က မကိုက်ပါဘူး။ ဒါပေမဲ့ arrow ကို ဆက်သုံးပြီး event.currentTarget ကို ဖတ်တာက ပိုရှင်းပါတယ်။

wrong-tool.js
const user = {
  name: "Ana",
  greetArrow: () => typeof this,        // not user
  greetMethod() { return this.name; },  // user
};
console.log(user.greetArrow(), user.greetMethod());

const Point = (x) => { this.x = x; };
try {
  new Point(1);
} catch (err) {
  console.log(err.message); // Point is not a constructor
}

Stack trace ထဲက နာမည်

const add = () => ... လို variable ထဲ assign လုပ်ထားတဲ့ arrow က variable နာမည်ကို function name အဖြစ် ရပါတယ်။ ဒါပေမဲ့ map ထဲ တိုက်ရိုက်ထည့်လိုက်တဲ့ inline arrow တွေက နာမည်မရှိလို့ error stack မှာ anonymous လို့ ပေါ်ပါတယ်။ ရှုပ်တဲ့ logic ကို နာမည်ပါတဲ့ function အဖြစ် ခွဲထုတ်ထားရင် debug လုပ်ရ ပိုလွယ်ပါတယ်။

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

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

ယနေ့ JavaScript codebase တွေမှာ arrow function ကို အများဆုံး တွေ့ရတာက array pipeline တွေထဲမှာပါ။ orders.filter((o) => o.paid).map((o) => o.total).reduce((sum, t) => sum + t, 0) လိုမျိုး step တစ်ခုချင်းစီကို line တစ်ကြောင်းနဲ့ ဖတ်လို့ရပါတယ်။ Promise chain တွေမှာလည်း .then((res) => res.json()) လို callback တိုလေးတွေအတွက် arrow ကို သုံးကြပါတယ်။

Class ထဲမှာ event handler ရေးတဲ့အခါ handleClick = () => { ... } လို class field arrow ကို သုံးကြပါတယ်။ ဒါဆိုရင် handler ကို button.addEventListener("click", this.handleClick) လို့ ပေးလိုက်လည်း this က instance ကို ဆက်ညွှန်းနေပါတယ်။ .bind(this) ထပ်ရေးစရာ မလိုတော့ပါဘူး။ React component အများစုလည်း arrow နဲ့ ရေးထားတာ တွေ့ရပါမယ်။

Team အများစုရဲ့ စည်းကမ်းက ရိုးရှင်းပါတယ်။ Callback နဲ့ function တိုလေးတွေကို arrow နဲ့ရေးပြီး object method၊ class method နဲ့ file ရဲ့ အဓိက function တွေကို ရိုးရိုး function ဒါမှမဟုတ် method syntax နဲ့ ရေးပါတယ်။ Linter (ESLint) မှာ prefer-arrow-callback လို rule တွေ ဖွင့်ထားပြီး ဒီစည်းကမ်းကို အလိုလို စစ်ခိုင်းကြပါတယ်။

အမှားများ

ဖြစ်လေ့ရှိတဲ့ အမှားများ

{ } ဖွင့်ပြီး return မေ့တာ

(x) => x * 2 ကို နောက်ပိုင်း log တစ်ကြောင်း ထည့်ချင်လို့ (x) => { console.log(x); x * 2; } လို့ ပြင်လိုက်တာနဲ့ return ပျောက်သွားပါတယ်။ map က undefined တွေနဲ့ ပြည့်နေတဲ့ array ကို ပြန်ပေးပါမယ်။ Braces ထည့်တိုင်း return ရှိမရှိ စစ်ပါ။

Object ကို ကွင်းမအုပ်ဘဲ ပြန်ပေးတာ

items.map((x) => { value: x }) က object မပြန်ပါဘူး။ { } ကို function body လို့ ဖတ်ပြီး value: ကို label အဖြစ် ယူလို့ပါ။ (x) => ({ value: x }) လို့ ကွင်းထဲ ထည့်ပါ။ Property နှစ်ခုနဲ့အထက် ပါရင်တော့ SyntaxError ဖြစ်တတ်လို့ သတိထားမိပေမယ့် တစ်ခုတည်းဆိုရင် အသံမထွက်ဘဲ မှားပါတယ်။

Object method ကို arrow နဲ့ ရေးတာ

const cart = { items: [], count: () => this.items.length } မှာ this က cart မဟုတ်ပါဘူး။ Module ထဲမှာဆိုရင် undefined ဖြစ်လို့ cart.count() က TypeError တက်ပါတယ်။ this လိုတဲ့ method တွေကို count() { ... } ဆိုတဲ့ method syntax နဲ့ပဲ ရေးပါ။

Arrow ထဲမှာ arguments ကို သုံးတာ

Arrow မှာ ကိုယ်ပိုင် arguments မရှိလို့ အပြင်ဘက် function ရဲ့ arguments ကို ရသွားတတ်ပါတယ်၊ ဒါမှမဟုတ် ReferenceError တက်ပါတယ်။ Argument အရေအတွက် မသေချာတဲ့ function ကို (...values) => ... ဆိုတဲ့ rest parameter နဲ့ ရေးပါ။

Mini challenge

Arrow function တွေနဲ့ ဈေးဝယ်လှည်း report

ဈေးဝယ်လှည်းထဲက item တွေကို report အဖြစ် ထုတ်ပေးတဲ့ code ကို ရေးပါ။ Helper function တွေကို arrow နဲ့ ရေးပြီး this လိုတဲ့ method တွေကိုတော့ method syntax နဲ့ ရေးပါ။ Method ထဲက callback တွေမှာ arrow ကို သုံးပြီး this.currency ကို ဖတ်ပါ။

  • withTax(price, rate) ကို default rate 0.1 ပါတဲ့ concise arrow အဖြစ် ရေးပါ
  • toLine(item) က { label, total } object ကို ပြန်ပေးပါ (ကွင်းအုပ်ဖို့ မမေ့ပါနဲ့)
  • cart.total() က reduce နဲ့ arrow callback သုံးပြီး item အားလုံးရဲ့ စုစုပေါင်းကို တွက်ပါ
  • cart.print() က forEach ထဲက arrow callback မှာ this.currency ကို သုံးပြီး line တစ်ကြောင်းစီ ထုတ်ပါ
cart-report.js
// TODO: concise arrow with a default rate of 0.1, rounded to 2 decimals
const withTax = undefined;

// TODO: arrow that returns { label: NAME IN CAPITALS, total: withTax(price * qty) }
const toLine = undefined;

const cart = {
  currency: "USD",
  items: [
    { name: "notebook", price: 4, qty: 3 },
    { name: "pen", price: 1.5, qty: 4 },
  ],
  total() {
    // TODO: reduce over this.items with an arrow callback
  },
  print() {
    // TODO: forEach with an arrow callback; read this.currency inside it
  },
};

cart.print();
console.log(`TOTAL ${cart.total()} ${cart.currency}`);

ရလဒ်: NOTEBOOK: 13.2 USD နဲ့ PEN: 6.6 USD ဆိုတဲ့ line နှစ်ကြောင်း ထွက်ပြီး နောက်ဆုံးမှာ TOTAL 19.8 USD ထွက်ပါမယ်။

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

Number ကို ဒဿမ နှစ်နေရာ ဖြတ်ချင်ရင် Math.round(value * 100) / 100 ကို သုံးပါ။ print() ကို arrow နဲ့ မရေးပါနဲ့၊ arrow ဖြစ်သွားရင် this က cart ဖြစ်မနေတော့ပါဘူး။

အဖြေ ကြည့်ရန်
cart-report.js
const withTax = (price, rate = 0.1) => Math.round(price * (1 + rate) * 100) / 100;

const toLine = (item) => ({
  label: item.name.toUpperCase(),
  total: withTax(item.price * item.qty),
});

const cart = {
  currency: "USD",
  items: [
    { name: "notebook", price: 4, qty: 3 },
    { name: "pen", price: 1.5, qty: 4 },
  ],
  total() {
    const sum = this.items.reduce((acc, item) => acc + toLine(item).total, 0);
    return Math.round(sum * 100) / 100;
  },
  print() {
    this.items.forEach((item) => {
      const line = toLine(item);
      console.log(`${line.label}: ${line.total} ${this.currency}`);
    });
  },
};

cart.print();
console.log(`TOTAL ${cart.total()} ${cart.currency}`);

Quick Quiz 1 / 3

const double = (x) => { x * 2 }; console.log(double(4)); က ဘာထုတ်မလဲ။

Quick Quiz 2 / 3

const user = { name: "Ana", hi: () => this.name }; မှာ user.hi() က "Ana" ကို ဘာကြောင့် မပြန်ပေးတာလဲ။

Quick Quiz 3 / 3

const Person = (name) => { this.name = name; }; new Person("Ana"); ကို run ရင် ဘာဖြစ်မလဲ။

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

  • Arrow function က (params) => expression ပုံစံနဲ့ function expression ကို တိုတိုရေးတာပါ
  • Expression တစ်ခုဆို အလိုလို return ဖြစ်ပြီး { } ဖွင့်ရင် return ကို ကိုယ်တိုင်ရေးရပါတယ်
  • Object ပြန်ပေးချင်ရင် ({ ... }) လို့ ကွင်းနဲ့ အုပ်ပါ
  • Arrow က this နဲ့ arguments ကို ရေးထားတဲ့နေရာကနေ ယူလို့ method ထဲက callback တွေအတွက် ကောင်းပါတယ်
  • Object method၊ constructor နဲ့ this လိုတဲ့ နေရာတွေမှာ ရိုးရိုး function ကို သုံးပါ

MDN — JavaScript Guide — MDN Web Docs

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

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

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

Arrow Functions | Thuta Learning