Professional Documents
Culture Documents
JavaScrpt From Beginner To Advanced
JavaScrpt From Beginner To Advanced
I
JavaScrpt from beginner to advanced
IV
អារម្ភកថា
សរៀបសរៀ្សដ្យ
ផេង ពុទ្ធ្រិទ្ធ
សបាេះេុម្ពស ើរទ្ី១ឆន្ំ២០២២
V
VI
មតិកា
៣.៨ Symbols.............................................................................................. 13
VII
៣.៩ The “typeof” Operator ............................................................................... 13
IX
២. ការសក្បើក្បា ់ comments ...................................................................................... 47
១. Objects ............................................................................................................. 48
៦.៣ Other variants: ?.(), ?.[] ................................. Error! Bookmark not defined.
១. Methods of primitives...................................................................................... 82
២. Numbers ......................................................................................................... 83
XI
៣. Strings............................................................................................................. 90
៤. Arrays .............................................................................................................. 98
៨.២ Excluding and transforming ៖ replacer ......... Error! Bookmark not defined.
១.២ The execution context and stack ................... Error! Bookmark not defined.
XIII
៤.២ “var” អាចក្បកា ម្ត្សហើយម្ត្សទ្ៀតសដ្យសក្បើសឈា្្េះដស្ដ ............................... 148
XIV
២. Class inheritance .......................................................................................... 187
២.៤ Overriding class fields៖ a tricky note ............ Error! Bookmark not defined.
៤.១ Internal និ្ external interface ....................... Error! Bookmark not defined.
XV
៣. Promise ......................................................................................................... 216
៧. Microtasks..................................................................................................... 238
XVI
១. ការស្ណនាំ្អំេី Modules ..................................................................................... 249
XVII
សម្សរៀនទ្ី១ ស ចរតីស្ណនាំ្ Introduction JavaScript
២. មេតុអ្វីបានជាគតូវមរៀន JavaScript?
សក្ៅេី ទ្ធភាេគា្្នស្ដនរំណត់រប ់ភាស្ JavaScript, មានសហតុ្ ជាសក្ចើនសទ្ៀតស្ដ
web developers សក្បើក្បា ់ភាស្ JavaScript៖
• JavaScript គឺ programming language ស្តម្ួយគត់ស្ដ ជាភាស្ native ក្មាប់
web browser
• JavaScript គឺជាភាស្សេញនិយម្ និ្ ំបូរអនរសក្បើក្បា ់សក្ចើន (rich community)
• JavaScript ជាភាស្ម្ួយស្ដ ងាយក្ ួ សរៀន ក្មាប់អនរចាប់ស្តើម្ដំបូ្ៗ
• JavaScript សក្បើបានទំ្្ Client side និ្ Server side
៣. ការចុឹះម្មឹះនិងរមបៀបមគបើគបាស្់ replit.com
1. ចូ សៅកាន់តំណភាជ្ប់ https://replit.com/
2. បស្កើត account សដ្យចុចបូតុ្ Signup ស្ដ សៅខា្ស ើស្្ំដដ
5. ចុ្សក្កាយសយើ្នឹ្ទ្ទ្ួ បានដូចរូបខា្សក្កាម្
មម្មរៀនទី២ ម្ូលដ្ឋានគ្រឹះមៅកនងភាសា
ុ JavaScript
១. Hello, World!
១.១ ការមគបើគបាស្់ document.write
ការសក្បើក្បា ់ document.write គឺសដើម្្បីបងាហ្ញ content សៅស ើ browser។
ក្ប ិនសបើសយើ្ចុចបូតុ្ Cancel ឬចុច keyboard “Esc”, prompt នឹ្សធែើការ return null។
ក្ប ិនបញ្េូ តដម្លសហើយចុចបូតុ្ Ok ឬចុច keyboard “Enter” សនាេះ prompt នឹ្សធែើការ return
តដម្លស្ដ សយើ្បានបញ្េូ ។
ក្បកា អញ្ញតតិសហើយ្ត ត
់ ដម្លភាល្ម្ៗ (Declare variable and assign into a single line) ៖
សយើ្អាចបតូរតដម្លរប ់អញ្ញតតិ
let message = "hello";
message = "Hi how are you?";
ការដ្រ់សឈា្្េះក្តឹម្ក្តូវ៖
let $ = 100;
let _ = "anything";
const fruit = "banana";
ការដ្រ់សឈា្្េះម្ិនក្តឹម្ក្តូវ៖
let 10 = "ten";
let function = 100;
៣.១ Number
ក្បសភទ្ទ្ិននន័យ Number តំណ្្ឱ្យទំ្្ integer និ្ floating point ។
let num = 123;
num = 12.345;
alert( num );
៣.២ BigInt
សៅរនុ្ភាស្ JavaScript, ក្បសភទ្ទ្ិននន័យជា Number ម្ិនអាចស ើ េី (253-1) ស្ដ ស មើ
ហនឹ្ 9007199152420991 ឬរ៍តិចជា្ -(253-1) ក្មាប់ស្្នរអវិជជមាន។ ទំ្្អ ់សនេះ
គឺជាការរំណត់រប ់ភាស្ JavaScript ។ ក្ប ិនជាសយើ្ច្់សក្បើក្បា ់ចំនួនស្ដ ស ើ េីសនេះ
សយើ្សក្បើក្បា ់ BigInt។
const bigInt = 1234567890123456789012345678901234567890n;
អរ្សរ “n” សៅខា្ចុ្ស ខតំណ្្ឱ្យ BigInt។
៣.៣ String
String ក្តូវស្តដ្រ់ single quotes ( ‘ ’ ) ឬ double quotes ( “ ” ) សៅសកា្ប
្ ្ខា្
text។
const greetings = "Hello Sir! How's it going?";
const book = 'Cambodia History';
console.log(book);
៣.៤ Boolean
ក្បសភទ្ទ្ិននន័យ Boolean មានស្តេីរតដម្លស្តបុសណ្្្េះគឺ true និ្ false។
const isTrue = true;
const isFalse = false;
console.log(isTrue, isFalse);
៣.៧ Objects
ក្បសភទ្ទ្ិននន័យស្ដ បានសរៀបរាប់ដូចខា្ស ើគឺក្តូវបានសៅថា “primitive value” ស្ដ តដម្ល
រប ់េួរវាអាច្ទុរនូវវតែុម្ួយ ( a single thing ) ស្តម្ួយបុសណ្្្េះ។ ចំស្នរឯ Objects គឺក្តូវបានសក្បើ
ក្មាប់្ទុរនូវ collections of data និ្ more complex entities។
const user = {
name: "Tola",
age: 18
};
៣.៨ Symbols
ក្មាប់ Symbols សនេះសយើ្នឹ្សរៀនសៅរនុ្សម្សរៀនទ្ី៤។ ការស្ដ ស ើរស ើ្សៅសេ សនេះគឺ
សដើម្្បីឱ្យអនរទំ្្អ ់គាន្ដឹ្ថា Data types សៅរនុ្ភាស្ JavaScript មានទំ្្អ ់៨។
លំហាត់
ចូរសធែើការបងាហ្ញក្បសភទ្ទ្ិននន័យទំ្្៧ស្ដ សយើ្បានសរៀនសហើយសៅខា្ស ើសដ្យសក្បើក្បា ់
alert ក្មាប់សធែើការបងាហញ
្ ។
៤. ការផ្លាស្់បរគបមេទទិ
តូ ននន័យ Type Conversion
ជាទ្ូសៅ operators និ្ functions ភាគសក្ចើនផ្ល្ ់បតូរក្បសភទ្តដម្លរប ់អញ្ញតតិស្ដ សយើ្បាន
សបាេះឱ្យសៅកាន់េួរវា សហើយេួរវាសធែើការផ្ល្ ់បតូរក្បសភទ្តដម្ល (ឬសៅថាក្បសភទ្ទ្ិននន័យរ៏បាន)
សនាេះសៅ ជាក្បសភទ្ទ្ិននន័យក្តឹម្ក្តូវម្ួយ។ ជាឧទហរណ៍ alert បានផ្ល្ ប
់ តូរក្បសភទ្ទ្ិននន័យសៅជា
String សដ្យ យ
ែ័ ក្បវតតិ និ្ arithmetic operations សធែកា
ើ រផ្ល្ ់បតូរតដម្លសៅជា Number។
… … …
3 assignment =
… … …
* ( … ) មានន័យថាសៅមានសទ្ៀត។
៦. ការមគបៀបម ៀប Comparisons
Comparisons គឺជាការសក្បៀបសធៀបរវា្តដម្លេីរ សហើយ ទ្ធ្ រប ់វាគឺមានស្តេីរសទ្គឺេិត
(true) និ្ម្ិនេិត (false)។
Comparisons មានដូចជា៖
• Greater than a > b
• Less than a<b
• Greater than or equals a >= b
• Less than or equals a <= b
• Equals a == b
• Not equals a != b
ឧទហរណ៍៖
console.log("2" > 1); // true
console.log(10 < "5"); // false
* សដើម្្បប
ី សញ្េៀ បញ្ហ្៖
1. រនុ្ការសក្បៀបសធៀបគួរស្តសក្បើក្បា ់ Strict equality ( === )
2. រុំសធែើការសក្បៀបសធៀបសដ្យសក្បើ >=, <=, >, < សៅសេ មាន null
លំហាត់
ចូរសក្បើក្បា ់ if, else if, សហើយនិ្ else សដើម្្បីបងាហ្ញដងៃនីម្ួយៗាម្រយៈ console.log ។
ឧទហរណ៍៖ let day = “Monday”; ដូចសនេះសៅស ើផ្ទ្ំ្ console ក្តូវបងាហ្ញថា “Today is
Monday.”។ សបើ let day = “Tuesday”; ដូចសនេះសៅស ើផ្ទ្ំ្ console ក្តូវបងាហ្ញថា “Today is
Tuesday.”។
៨. Logical operators
សៅរនុ្ JavaScript programming មានបួន logical operators។
1. || ( OR ) logical operator
2. && ( AND ) logical operator
3. ! ( NOT ) logical operator
4. ?? ( Nullish Coalescing ) logical operator
ឧទហរណ៍២៖
let student;
student = student ?? "John Doe";
លំហាត់
ចូរររអញ្ញតតិស្ដ មានតដម្លធំជា្សគរនុ្ចំសណ្ម្អញ្ញតតិទំ្្បួនខា្សក្កាម្សដ្យសក្បើក្បា ់
if, else if, else រួម្ទំ្ logical operator។
let a = 10;
let b = -8;
let c = 12;
let d = 2;
}
while loop នឹ្ដំសណើរការ block code សៅសេ ស្ដ រខខណឌ (condition) េិតស្ត
បុសណ្្្េះ។
ឧទហរណ៍៖
ដំសណើរការ៖
} while (condition);
ឧទហរណ៍៖
ដំសណើរការ៖
}
ឧទហរណ៍៖
for loop
begin let i = 0; ដំសណើរការស្តម្ត្គត់សៅរនុ្ for loop
condition i < 5; េិនិត្យរា ់រ្ែិ ជុំនីម្ួយៗរប ់ loop ( loop
iteration ) ក្ប ិនសបើម្ិនេិត loop
នឹ្ក្តូវបានបញ្េប់។
body loop console.log(“i: ” , i); ដំសណើរការម្ត្សហើយម្ត្សទ្ៀតសៅសេ
រខខណឌេិត
step i++ សធែើការសរើនតដម្លរប ់អញ្ញតតិ “i”
ម្ត្ម្ួយរា ់រ្ែិ ជុំរប ់ loop (
ម្ួយជុំសរើនតដម្លម្ួយ )
លំហាត់
default:
block code
break;
}
switch(day) {
case 'Monday':
console.log(`Today is ${day}.`);
break;
case 'Tuesday':
console.log(`Today is ${day}.`);
break;
case 'Wednesday':
console.log(`Today is ${day}.`);
break;
case 'Thursday':
console.log(`Today is ${day}.`);
break;
case 'Friday':
console.log(`Today is ${day}.`);
break;
case 'Saturday':
console.log(`Today is ${day}.`);
break;
case 'Sunday':
console.log(`Today is ${day}.`);
break;
default:
console.log(`Unknown day!`);
break;
}
ឧទហរណ៍៖
const num = 4;
switch(num) {
case 1:
case 2:
case 3:
console.log(`Num is in range {1-3}.`);
break;
default:
console.log(`Num is not in range {1-3}.`);
break;
}
លំហាត់
ចូរសក្បើក្បា ់ switch statement សដើម្្បីសធែើការបងាហ្ញសឈា្្េះស្ខម្ួយរនុ្ចំសណ្ម្ស្ខទំ្្១២
សៅសេ ស្ដ អនរសក្បើក្បា ់ ( user ) សធែើការបញ្េូ តដម្លាម្រយៈ prompt ។ ឧទហរណ៍៖
សយើ្មាន អញ្ញតតិ “month” ម្ួយស មើនឹ្ prompt ( “បញ្េូ ស្ខ១រន្
ុ ចំសណ្ម្ទំ្១២” );
សហើយសៅសេ ស្ដ user បញ្េូ “ឧ ភា” ក្តូវបងាហ្ញ ទ្ធ្ សៅស ើផ្ទ្ំ្ console ថា
“ស្ខសនេះគឺជាស្ខឧ ភា” សបើ user បញ្េូ “ម្ិងុនា” ក្តូវបងាហ្ញ ទ្ធ្ សៅស ើផ្ទ្ំ្ console ថា
“ស្ខសនេះគឺជាស្ខម្ិងុនា”។
១១. Functions
Functions គឺជាបណ្តំដនរូដ ស្ដ សយើ្សក្បើ ក្មាប់សដ្េះក្ស្យបញ្ហ្ជារ់លារ់ណ្ម្ួយ។
ស្រៈ ំខាន់រប ់ functions មានដូចជា៖
1. ងាយក្ ួ រនុ្រររំហុ ្គ្ និ្សធែើការស្រតក្ម្ូវស្តម្ួយរស្នល្ រស្នល្ស្្ស្សទ្ៀតរ៏ក្តូវ
បានស្រតក្ម្ូវ
2. រស រម្ួយដ្សក្បើបានសក្ចើនរស្នល្សដ្យេុំចាំបាច់ រស ររូដដស្ដ ៗ
3. ក្មាប់សដ្េះក្ស្យបញ្ហ្ មុគស្្្ញ
console.log("Hello Rotana!");
}
សៅរនុ្ function sayHello, អញ្ញតតិ “greetings” គឺជា local variable។ សយើ្ម្ិនអាចយរ
“greetings” ម្រសក្បើសៅខា្សក្ៅ function sayHello បានសទ្។ សបើសយើ្យរម្រសក្បើសៅខា្សក្ៅ
សនាេះនឹ្មាន Error សរើតស ើ្។
១១.៤ Parameters
សយើ្អាចបញ្េូនទ្ិននន័យសៅកាន់ function block ាម្រយៈ parameters។
sayHello();
if (hello == undefined) {
hello = "Hey, guy!";
sayHello();
សៅរនុ្ function “sum” សយើ្បានសធែើការ return num1 + num2; សៅសេ សយើ្ call
សៅ function “sum” សយើ្បានសបាេះ argument (2) និ្ argument (5) សៅជាម្ួយ ដូសចនេះ
function “sum” បាន return តដម្ល 7 ម្រវិញសហើយសយើ្សធែើការសបាេះបនតសៅឱ្យអញ្ញតតិ “result”
បនាទ្ប់ម្រសយើ្យរតដម្លសនាេះបងាហ្ញសៅស ផ្
ើ ទ្ំ្ console ាម្រយៈ console.log។
ចំណ្ំ៖ function ស្ដ អត់មាន return ឬរ៏ return ទ្សទ្, function សនាេះស មើនឹ្ return
undefined ។
• function អត់មាន return
function sayHi() {
console.log("Hi, there!");
}
console.log(sayHi() == undefined);
console.log(sum(1, 3) == undefined);
console.log("Hello Rotana!");
};
• Function declaration
o សៅសេ ស្ដ JavaScript ដំសណើរការរម្មវិធគ
ី ឺវាសធែើការ execute function
declaration ម្ុនសគ បនាទប
្ ់ម្របានវាសធែើការេីខា្ស ើចុេះម្រសក្កាម្។ មានន័យថាសទេះ
បីជា function declaration រស រសៅខា្ស ើសគឬសៅខា្សក្កាម្សគរ៏
JavaScript សធែើការ execute វាម្ុនសគដស្ដ ។
sum(10, 8); // ទ្ធ្ គឺ 18 បងាហញ
្ សៅស ផ្
ើ ទ្ំ្ console សដ្យម្ិនមាន Error
console.log(num1 + num2);
• Function expressions
o សៅសេ ស្ដ JavaScript ដំសណើរការរម្មវិធីគឺវាម្ិនបានចាត់ទ្ុរ function
expressions ថាជា រខណៈេិស ស្ដ ក្តូវ execute ម្ុនសគសទ្។ ដូចសនេះ
ការក្បកា function expressions សៅរស្នល្ណ្ និ្ការ call សៅ function
ម្រសក្បើសៅរស្នល្ណ្គឺជាបញ្ហ្ស្ដ សយើ្ក្តូវយ ់ដឹ្ទំ្្អ ់គាន្។
console.log("Hello Rotana!");
};
console.log("Hello Rotana!");
};
sayHello(); // ទ្ធ្ “Hello Rotana” បងាហញ
្ សៅស ផ្
ើ ទ្ំ្ console
• Function declaration
console.log(calculateTotal());
console.log(sum(pen, book)); // *
• Function expressions
ឥ ូវសយើ្យរ function ខា្ស ើម្រសក្បើដស្ដ សដ្យផ្ល្ ់បតូរ function sum េី function
declaration សៅជា function expressions។
let sum;
let pen = 10;
let book = 20;
let tax = 1;
console.log(calculateTotal());
console.log(sum(pen, book)); // **
let result = a + b;
return result;
};
លំហាត់
ចូរផ្ល្ ់បតូរ functions ខា្សក្កាម្សៅជា arrow functions ទំ្្អ ់។ ក្ប ិនសបើ function
សនាេះមាន body ស្តម្ួយជួរសទ្ក្តូវស្តសក្បើក្បា ់រសបៀបខលីសដ្យម្ិនមាន ( { } )។
let sum;
let pen = 10;
let book = 20;
let tax = 1;
console.log(calculateTotal());
console.log(sum(pen, book));
មម្មរៀនទី៣ ្ុែភាពរបស្់កដ
ូ Code quality
១. Coding style
សគា ការណ៍ រស ររូដស្ដ អនរ រស ររូដទំ្្អ ់គួរសគារេាម្គឺការ រស ររូដរប ់សយើ្
ក្តូវមានរសបៀបសរៀបរយសហើយងាយក្ ួ រនុ្ការសម្ើ (read) ក្មាប់ទំ្្ខលួនឯ្ និ្អនរ រស ររូដ
ស្្ស្សទ្ៀត។
• Not good ☹
if (x == 1)
console.log("x: ", x);
• Not good ☹
if (x == 1) { console.log("x: ", x); }
• Good 😊
if (x == 1) {
console.log("x: ", x);
}
១.២ គបណវងកូដកនងម្ួ
ុ យជួរមដក
សបើសយើ្ រស ររូដស្វ្រនុ្ម្ួយជួរសដរៗគឺេិបារសម្ើ ទំ្្សគទំ្្សយើ្ ដូចសនេះសយើ្ រស រ
រុំឱ្យស្វ្សេរ សបើ text ហនឹ្ស្វ្សយើ្គួរចុេះបនាទ្ប់។
ចំណ្ំ្៖ សបើសយើ្សក្បើ single quotes (‘ ’) ឬ double quotes (“ ”)
សហើយចុេះបនាទ្ត់សនាេះនឹ្មាន Error ។ ដំសណ្េះក្ស្យគឺសយើ្ក្តូវសក្បើ backtick quotes (` `)។
• Not good ☹
console.log("Lorem ipsum dolor sit amet, consectetur adipisicing elit. Lore");
• Error ☹
console.log("Lorem ipsum dolor sit amet, consectetur adipisicing elit.
Aspernatur, quasi? Vel consequatur sunt, necessitatibus aliquid delectus
asperiores eos");
• Good 😊
console.log(`
Lorem ipsum dolor sit amet consectetur
adipisicing elit. Unde aliquam voluptatibus
iusto labore adipisci, sint consequuntur
`);
• ការចុេះបនាទ្ត់ជួរឈរ
function sum(a, b) {
return a + b;
}
<= ទ្ុរចសនាល្េះម្ួយបនាទ្ត់
console.log("Sum: ", sum(12, 3));
១.៤ Semicolons ;
By default JavaScript នឹ្សធែើការដ្រ់ semicolons សៅក្ត្់ចំនុច line break។ បុស្នតសយើ្
គប្បីសក្បើ semicolons ; រា ់ line break សដ្យខលួនឯ្សជៀ វា្មាន Error ស្ដ េិបារនឹ្
ស្ ែ្ររ។
• គប្បីសជៀ វា្ ☹
if ( x > 0) {
if (x == y) {
if (x > z) {
}
}
}
២. ការមគបើគបាស្់ comments
ជាទ្ូសៅសយើ្សក្បើក្បា ់ comments សដើម្្បីេិេណ៌នាអំេីដំសណើរការរប ់រូដ។ Comments
មានដូចជា៖
• single-line : //
• multi-line : /* … */ និ្ <!-- … -->
function login() {
... block code
}
មម្មរៀនទី៤ Objects
១. Objects
សៅរនុ្សម្សរៀនទ្ី២សយើ្បានសរៀនអំេីក្បសភទ្ទ្ិននន័យនិ្បានស្គ្ ់ objects បនតិចបនតួចស្ដរ។
សៅរនុ្សម្សរៀនសនេះសយើ្នឹ្សធែើការ ំអិតអំេី objects ។ Objects គឺជាក្បសភទ្ reference type វា
ខុ េី primitive type មានដូចជា String Number Boolean ។ ។ សយើ្សក្បើ objects សដើម្្បី
្ទុរទ្ិននន័យសក្ចើនក្បសភទ្ (to store collections of various data) សហើយធាតុ (properties)
ស្ដ សៅរនុ្ Objects ក្តូវបានសគសៅថា key/value pairs។ សៅរនុ្ភាស្ខលេះធាតុស្ដ សៅរនុ្
objects ក្តូវបានសគសៅថា property/value, សៅរនុ្ភាស្ JavaScript សយើ្រ៏អាចសៅថា
property/value បានស្ដរ។ ដូសចនេះក្ប ិនសបើសយើ្អានស ៀវសៅ ឬសម្ើ សម្សរៀនជាវើសដអូ សហើយសគ
សៅថា key/value pairs ឬរ៏ property/value សយើ្អាចដឹ្បានថាវាគឺ ុទ្ធស្តជាធាតុ
(properties) សៅរនុ្ objects ។ ឥ ូវសយើ្ម្រសម្ើ េីរសបៀបបស្កើត objects វិញម្ត្៖
• រសបៀបទ្ី១៖ object constructor
let animal = new Object();
រសបៀបទ្ី១សនេះគឺសយើ្បស្កើត object សដ្យសក្បើ object constructor “new Object()”។
• សក្បើ camelCase
eyeColor
ឧទហរណ៍៖
let dog = {
color: "white",
"eye color": "black",
weight: 12
};
farm[animal] = 20;
farm.sheep = 50;
console.log("There are ", farm.sheep, " sheep in the farm.");
const user = {
name: name,
age: age,
height: height
};
សៅរនុ្ object user សយើ្ស ើញថា value “name, age, និ្ height” គឺមានសឈា្្េះ ដូចនឹ្
key “name, age, និ្ height” ។ សៅរនុ្ភាស្ JavaScript ក្ប ន
ិ សបើ key និ្ value
មានសឈា្្េះដូចគាន្ស្បបសនេះសយើ្អាច រស រជាទ្ក្ម្្់ខលីបាន គឺ រស រដូចខា្សក្កាម្។
let name = "Marry";
let age = 22;
let height = 1.7;
const user = {
name,
age,
height
};
console.log(user[10]);
console.log(user["10"]);
"8": "eight"
};
ឧទហរណ៍ទ្ី២៖
const orderedObject = {
"2": "two",
num: 10,
fruit: "apple",
"8": "eight"
};
លំហាត់
ចូរ រស រ JavaScript program សដើម្្បីសធែើការ ុប properties រប ់ object cart ណ្ស្ដ
ជា integer property។
const cart = {
bag: 20,
"fashion shoes": 100,
"10": 29,
shoes: 39,
32: 43
};
hint៖ សក្បើក្បា ់ built-in function “Number” ឬរ៏ unary + សដើម្្បីដឹ្ថាធាតុសនាេះជា
integer ឬម្ិនស្ម្ន។
• Object.assign
let apple = {
color: "red",
shape: "round"
};
let clone = Object.assign({}, apple);
clone.color = "green";
console.log("Object clone: ", clone); // color = “green”
ឧទហរណ៍ខា្ស ើសៅរន្
ុ method fullname សយើ្សក្បើ this សដើម្្បី access properties (
firstname, lastname ) បនាទ្ប់ម្រសយើ្ភាជ្ប់ properties ទំ្្េីរសដ្យ unary operator + និ្
white space “ ” សដើម្្បីបស្កើតបានជាសឈា្្េះសេញម្ួយ។
១.៦ “ in ” operator
សដើម្្បីេិនិត្យសម្ើ ថា property ម្ួយហនឹ្ ែិតសៅរនុ្ object ម្ួយហនឹ្ស្ដរឬសទ្ សយើ្សក្បើក្បា ់
“in” operator សហើយតដម្លស្ដ វា returns ក្ត ប់ម្រវិញមានស្តេីរសទ្គឺេិត និ្ម្ិនេិត។
const user = {
10: "ten",
};
function displayName() {
console.log( this.name );
}
user.func = displayName;
admin.func = displayName;
ចំណ្ំ៖ សៅសេ ស្ដ សយើ្ call សៅ function សដ្យគា្្ន object, this ស មើនឹ្ undefined។
function displayName() {
console.log( this.name );
}
displayName(); // undefined
let marry = {
age: 18,
height: 1.62,
weight: 42
};
ឧទហរណ៍៖
function Human(age, height, weight) {
this.age = age;
this.height = height;
this.weight = weight;
}
ចំណ្ំ៖
• Implicitly មានន័យថាអែៗ
ី ក្តូវបានសរៀបចំស ើ្ទ្ុរជាម្ុនសដ្យភាស្ JavaScript
• Explicitly មានន័យថាអែីៗក្តូវបាន រស រស ើ្, បស្កើតស ើ្, សរៀបចំស ើ្សដ្យ
អនរ រស ររូដផ្ទ្ ់
• ម្ូ សហតុស្ដ សក្បើក្បា ់ constructor functions គឺ reusable
• សយើ្ម្ិនអាចសក្បើក្បា ់ arrow functions ជា constructor functions បានសទ្
េីសក្ េះ arrow functions ម្ិនមាន “this”
ឧទហរណ៍ទ្ី១៖
function Human(firstname, lastname) {
this.firstname = firstname;
this.lastname = lastname;
const fullname = this.firstname + " " + this.lastname;
return {
fullname: fullname
};
}
ឧទហរណ៍ទ្ី២៖
function Human(firstname, lastname) {
this.firstname = firstname;
this.lastname = lastname;
return 10 + 2;
}
this.firstname = firstname;
this.lastname = lastname;
this.fullname = function() {
console.log(`Fullname: ${this.firstname} ${this.lastname}`);
}
}
លំហាត់
ចូរបស្ម្ល្ object ខា្សក្កាម្ឱ្យសៅជា constructor function សហើយសធែើការបងាហ្ញតដម្លរប ់វា
ាម្រយៈ console.log។
const student = {
name : "Makara",
class_name: "12A",
grade : 12
};
console.log(user.address); // undefined
console.log(user.address.line1); // error occurs
console.log(user.address); // undefined
console.log(user.address && user.address.line1); // undefined
ឧទហរណ៍ user?.address ៖
ដំសណើរការរប ់វាគឺក្ប ិនសបើតដម្លសៅខា្ស្ែ្រប ់វា “ ?. ” ជា Object សនាេះវានឹ្បនត access
សៅខា្ តំំារប ់វាសទ្ៀតបុស្នតសបើតដម្លខា្ស្ែ្រប ់វាម្ិនស្ម្នជា Object សទ្ វានឹ្បញ្្ឈប់ក្តឹម្នឹ្។
ម្ូ សហតុស្ដ សយើ្ក្តូវសក្បើវាសនាេះេីសក្ េះសេ ខលេះសយើ្ម្ិនអាចដឹ្ម្ុនបានសទ្ថាអញ្ញតតិសនាេះជា
object ឬម្ិនស្ម្ន សបើវាជា object វិញសយើ្រ៏ម្ិនដឹ្ស្ដ ថា properties រប ់វាស្ដ សយើ្ក្តូវការ
access សនាេះមានតដម្លជា object ឬរ៏អត់។ ឧទហរណ៍សយើ្ទញទ្ិននន័យ user េី database ម្រ
សហើយច្់បានអា ័យដ្ឋន
្ រប ់ user សនាេះ, ក្ប ិនសបើអា ័យដ្ឋ្នសនាេះមានសយើ្នឹ្ទ្ទ្ួ បាន
ទ្ធ្ ដូចស្ដ សយើ្ច្់បាន បុស្នតសបើអត់មានវិញ សយើ្ច្់ឱ្យតដម្លសនាេះស មើនឹ្ undefined ជាជា្
error សហើយបញ្េប់រម្មវិធីរប ់សយើ្។
console.log(user.address); // undefined
console.log(user.address?.line1); // undefined
៦. Symbol type
Object keys អាចមានស្តេីរក្បសភទ្បុសណ្្្េះគឺ string type និ្ symbol type ម្ិនអាចជា
numbers ឬរ៏ Booleans ជាដ្ច់ខាត។
៦.១ Symbols
“symbols” តំណ្្ឱ្យ unique identifier។ សហើយសយើ្អាចបស្កើតវាបានសដ្យសក្បើក្បា ់
Symbol()។
const id = Symbol();
warning ៖ សៅសេ ស្ដ សយើ្សក្បើ Symbol ជាម្ួយ built-in function “alert” នឹ្មាន Error
សរើតស ើ្សដ្យស្រស្ត default behavior រប ់ “alert” គឺបស្ម្ល្តដម្លទំ្្អ ់ស្ដ ែិតសៅរនុ្វ្់
ក្រចររប ់វាសៅជា string បុស្នត ក្មាប់ symbol គឺជា special type ម្ួយស្ដ function “alert”
ម្ិនអាចបស្ម្ល្វាសៅជា string សដ្យខលួនឯ្សទ្ដូចសនេះសយើ្ក្តូវសក្បើ array method “toString()”
សដើម្្បីជំនួយ។
const studentId1 = Symbol("studentId");
const studentId2 = Symbol("studentId");
alert(studentId1.toString()); // Symbol(studentId)
const student = {
[studentId]: "0001"
};
សៅសេ ស្ដ សយើ្ access symbol សយើ្ក្តូវស្តសក្បើ square brackets “[ ]” ដូចគាន្ ម្ិនអាច
សក្បើនិម្ិតត ញ្ញ្ dot “ . ” បានសទ្។
console.log(student[studentId]); // 0001
const student = {
[studentId]: "0001",
name: "Heng leaphea",
age: 21,
gender: "female"
};
៦.៥ Symbol.keyFor
សៅសេ ស្ដ សយើ្ដឹ្ថា identifier ម្ួយជាក្បសភទ្ symbol ស្តក្ប ិនជាសយើ្ម្ិនដឹ្ថាវាជា
symbol ឬរ៏ជា global symbol សទ្, គឺសយើ្អាចសក្បើ Symbol.keyFor សដើម្្បីសធែើការេិនិត្យ។
console.log(Symbol.keyFor(local)); // undefined
console.log(Symbol.keyFor(global)); // global
មម្មរៀនទី៥ គបមេទទិនននយ
័ Data types
១. Methods of primitives
សយើ្បានសរៀនសក្ចើនម្រសហើយអំេី object methods, ម្ិនក្តឹម្ស្ត object សទ្ស្ដ អាចមាន
methods ូម្្បីស្ត primitives រ៏អាចមាន methods ស្ដរ។ សៅសេ ស្ដ សយើ្សក្បើ methods
ជាម្ួយ primitive, primitive សនាេះក្តូវបានចាត់ទ្ុរថាជា object ( a primitive as an object )។
ម្ុននឹ្បនតសយើ្រំ ឹរអំេី primitives បនតិច៖
• Primitives
o តដម្លរប ់វាជាក្បសភទ្ primitive
o សៅសេ ស្ដ សយើ្ចម្ល្តដម្លរប ់ primitive តដម្លវាក្តូវបានចម្ល្ as a whole
o សៅរនុ្ភាស្ JavaScript មាន៧ primitive types ៖ string, number,
bigint, Boolean, symbol, null, and undefined។
ដំសណើរការ៖
ឧទហរណ៍ទ្ី២៖
let num = 102.20394;
num = num.toFixed(2);
console.log(num); // 102.20
២. Numbers
សៅរនុ្ភាស្ JavaScript, Numbers មានេីរក្បសភទ្។
1. Regular numbers គឺក្តូវបាន្ទុរតដម្លរនុ្ទ្ក្ម្្់ 64-bit format IEEE-754 ឬសយើ្អាច
សៅម្្ា្្សទ្ៀតថា “ double precision floating point numbers ” ។
2. BigInt numbers, តំណ្្ឱ្យស ខសក្ចើនខទ្់ស្ដ regular numbers ម្ិនអាចមានស ើ ។
ស ខរប ់ regular numbers គឺមានរំណត់ម្ិនអាចស ើ េី 253 និ្ម្ិនអាចតិចជា្ -253។
ដូចសនេះក្ប ិនសបើសយើ្ច្់សក្បើស ើ សនេះគឺសយើ្ក្តូវសក្បើស ខ bigint។
២.១ មគចើនរមបៀបកនងការស្រមស្រ
ុ number
• regular way
let num = 1000000;
• ជាម្ួយនឹ្អរ្សរ e
let num = 1e6; // e6 ស មើនឹ្ស ខ ូន្យ៦ដ្ សបើ e10 ស ខ ូន្យ១០ដ្ ។ ។
២.២ toString(base)
Method “ num.toString(base) ” returns string ស្ដ តំណ្្ឱ្យស ខសៅរនុ្ក្បេ័នធ
numeral ជាម្ួយ base ( សគា ) ស្ដ សយើ្បាន្ត ់ឱ្យ។ By default សគា ស្ដ return េី
toString() គឺសគា ១០។
• សគា មានដូចជា 2, 8, 10, 16, និ្ 36
o សគា 2 តំណ្្ឱ្យ binary, អាចជាស ខ 0 ឬរ៏ 1
o សគា 8 តំណ្្ឱ្យ octal, ស ខមានេី 0-7
o សគា 16 តំណ្្ឱ្យ hex, ស ខមានេី 0-9 និ្ A-F
o សគា 36 គឺជាសគា ស្ដ ធំបំ្ុតសៅរនុ្ក្បេ័នធ numeral, , ស ខមានេី 0-9 និ្េី
A-Z។ រខណៈេិស រប ់សគា 36 គឺសយើ្បស្ម្ល្ស ខេីស្វ្ឱ្យសៅជាខលី។
console.log(2945289..toString(36)); //1r4ll
ចំណ្ំ្៖ សៅសេ ស្ដ សយើ្សក្បើស ខផ្ទ្ ់ជាម្ួយ toString() សយើ្ក្តូវបស្នែម្និម្ិតត ញ្ញ្ dot ( . )
ម្ួយសទ្ៀតសដើម្្បីឱ្យ JavaScript ដឹ្ថាវាម្ិនស្ម្នជាស ខស្ដ សៅសក្កាយសរ្បៀ សទ្ ស្តសបើសយើ្អត់សក្បើ
សនាេះ JavaScript នឹ្គិតថាវាជាស ខសក្កាយសរ្បៀ សដ្យស្រស្តស ខសក្កាយសរ្បៀ ម្ិនអាចជា
អរ្សរបានសទ្ដូចសនេះវានឹ្ return error ក្ត ប់ម្រវិញ។ ទ្នទឹម្នឹ្សនេះសយើ្រ៏អាចសក្បើវ្់ក្រចរជំនួ
(2945289).toString(36);។
២.៣ Rounding
Rounding ( ប្គត់ ) គឺជា math operations ស្ដ សយើ្សក្បើញឹរញាប់ជា្សគ។
• Math.ceil
ប្គត់ស ើ្៖ 3.1 សៅជា 4, -2.2 សៅជា -2
• Math.round
ប្គត់សៅខា្ស ខស្ដ ជិតបំ្ុត៖ 3.1, 3.2, 3.3, 3.4 សៅជា 3។
3.5, 3.6, 3.7, 3.8, 3.9 សៅជា 4 ។
• Math.trunc
ុបស ខសក្កាយសរ្បៀ សចា ទំ្្អ ់៖
3.1 សៅជា 3
3.6 សៅជា 3
-2.8 សៅជា -2
ចំណ្ំ៖ (0.1 + 0.2) ម្ិនស មើនឹ្ 0.3 សទ្, សដ្យស្រស្ត number ក្តូវបាន្ទុរសៅរនុ្ memory
ជាទ្ក្ម្្់ binary ( 1 និ្ 0 )។ សៅរនុ្ក្បេ័នធ binary number, ្ ស្ចរ 1/10 ទ្ធ្ ស ខ
សក្កាយសរ្បៀ គឺគា្នទ្ីបញ្េប់ ដូសចនេះគា្្នវិធីស្ញ្ច តណ្ស្ដ ធានាថាអាច្ទុរតដម្ល 0.1 គឺ 0.1 និ្ 0.2
គឺ 0.2 សៅរនុ្ក្បេ័នធ binary number សទ្។
console.log(0.1 + 0.2 == 0.3) // false;
console.log(0.3); // 0.3
console.log(0.1 + 0.2 ); // 0.30000000000000004
console.log(sum); // "0.30"
console.log(typeof sum) // string
ឧទហរណ៍ទ្ី២៖
const num1 = " 12.345+";
ឧទហរណ៍ទ្ី៣៖
const num2 = "id245";
• Math.pow(n, power)
n គឺជាស ខ ( natural number ) រើឯ power គឺជា ែ័យគុណ។
ឧទហរណ៍៖
console.log(Math.pow(2, 5)); //32
លំហាត់
ចូរបស្កើត JavaScript function ម្ួយសដើម្្បីេិនិត្យសម្ើ ថាសតើ តដម្លស្ដ បានសបាេះសៅាម្រយៈ
parameter រប ់ function សនាេះជា natural number ឬម្ិនស្ម្ន។
ចំណ្ំ៖ Natural numbers គឺជាស ខស្ដ ចាប់េី 0 ស ើ្សៅ 0, 1, 2, 3, 4 …។
ឧទហរណ៍៖
isNaturalNumber(-15); // not a natural number
isNaturalNumber(20.8); // not a natural number
isNaturalNumber(15); // yes, it is a natural number
៣. Strings
សៅរនុ្ភាស្ JavaScript, ទ្ិននន័យជា text ក្តូវបាន្ទុរសៅរនុ្ memory ជាក្បសភទ្
strings។ ទ្ក្ម្្់ដ្ទខា្រនុ្រប ់ strings គឺ UTF-16។
៣.១ Quotes
Strings គឺក្តូវបានសកា្្ប ្ខា្សដ្យ single quotes, double quotes ឬ backticks។
let single = 'single-quoted';
let double = "double-quoted";
console.log(`
Shoes' price: ${shoes}
Bag's price: ${bag}
Total: ${shoes + bag}
`);
ភាេបត់ស្បនរប ់ backticks គឺសយើ្អាចចុេះបនាទ្ត់បុនា្នជួររ៏បាន, ស ើ េីសនេះសយើ្អាច
សៅអញ្ញតតិស្្ស្ម្រសក្បើរ៏បានសហើយអញ្ញតតិទំ្្សនាេះម្ិនថា functions, objects, array ។ ។
ុទ្ធស្តអាចសក្បើបានទំ្្អ ់ ម្្ា្្សទ្ៀតទ្ក្ម្្់ស្បបសនេះ “ `${…}` ” ក្តូវបានសគឱ្យសឈា្្េះថា template
string។
ឧទហរណ៍ backslash \ ៖
console.log('I\'m a student.'); // I'm a student
console.log(`Backslash: \\`); // Backslash: \
សៅរនុ្ string សយើ្សក្បើ backslash (\) សដើម្្បី escape character។ ឧទហរណ៍ខា្ស ើ
ក្ប ិនសបើសយើ្ម្ិនសក្បើ backslash (\) “I\’m a student” នឹ្ម្ិនក្តូវបានបងាហ្ញស ើផ្ទ្ំ្ console
សទ្េីសក្ េះសយើ្បានសក្បើ single quotes សដើម្្បីសកា្្ប string ដូចសនេះសយើ្ម្ិនអាចសក្បើ single quotes
សៅរនុ្ single quotes បានសទ្ក្ប ិនជាសយើ្ចាំ្បាច់សក្បើ សយើ្ក្តូវសក្បើ backslash (\) សដើម្្បីឱ្យ
JavaScript engine ដឹ្ថា single quotes ស្ដ សៅខា្រនុ្គឺម្ិនស្ម្នចុ្បញ្េប់ដន string
រប ់សយើ្សទ្។ សដ្យស្រស្តសៅរនុ្ string អត់មាន backslash (\) សទ្ក្ប ិនសបើសយើ្ច្់សក្បើវា
សៅរនុ្ string សយើ្ក្តូវស្តសក្បើវា ទួន (\\)។
console.log(flower[0]); // s
console.log(flower.charAt(0)); // s
console.log(flower[flower.length - 1]); // r
console.log(flower[12]); // undefined
console.log(flower.charAt(12)); // empty string ""
cat = "Meow";
console.log(cat); // Meow
console.log(dog.toLowerCase()); // ah dam
console.log(dog.toUpperCase()); // AH DAM
console.log(dog[dog.length-1].toUpperCase()); // M
console.log(sentence.indexOf("are")); // 6
console.log(sentence.indexOf("re")); // 3
console.log(sentence.indexOf("re", 5)); // 7 (start from index 5)
• str.lastIndexOf(substring, position)
ដំសណើរការ lastIndexOf គឺបញ្ចញ្រ្ េី indexOf គឺវាសធែើការស្ ែ្ររេីទ្ីាំ្្ចុ្បំ្ុត
ដន string ម្រវិញ។
let phrase = "as soon as";
console.log(phrase.indexOf("as")); // 0
console.log(phrase.lastIndexOf("as")); // 8
console.log(phrase.includes("soon")); // true
console.log(phrase.includes("sky")); // false
console.log(phrase.startsWith("soon")); // false
console.log(phrase.startsWith("As")); // false
console.log(phrase.startsWith("as")); // true
console.log(phrase.endsWith("more")); // false
console.log(phrase.endsWith("gain")); // true
• str.substring(start [, end])
substring returns តដម្លម្ួយស្្នររប ់ string េីចសនាល្េះរវា្ start និ្ end។ វាក្ សដៀ្
សៅនឹ្ slice ស្ដរបុស្នត substring អាចឱ្យសយើ្សក្បើតដម្ល start ធំជា្ end។ បុស្នតសយើ្ម្ិនសក្បើ
ស ខអវិជជមានដូចសៅរនុ្ slice បានសទ្។
let fruit = "pineapple";
console.log(fruit.substring(3, 9)); //eapple
console.log(fruit.substring(9, 3)); //eapple
• str.substr(start [, length])
substr returns តដម្លម្ួយស្្នររប ់ string ចាប់េី start សៅ, ជាម្ួយនឹ្ length
ស្ដ សយើ្បាន្ត ់ឱ្យ។ វាខុ េី methods េីរខា្ស ើ, សៅរនុ្ substr គឺសយើ្អាចសក្បើ
second parameter (length) សដើម្្បីរំណត់ចំនួនតួអរ្សរស្ដ សយើ្ច្់បាន។
let fruit = "pineapple";
ារា្ ASCII៖
លំហាត់
៤. Arrays
សយើ្អាចសក្បើ Array សដើម្្បី្ទុរទ្ិននន័យាម្ ំដ្ប់, ឧទហរណ៍៖ ទ្ី១ ទ្ី២ ទ្ី៣ ទ្ី៤ ។ ។
Array គឺជា special data structure ម្ួយស្ដ សយើ្អាច្ទុរទ្ិននន័យបានសក្ចើនក្បសភទ្និ្ាម្
ំដ្ប់ ំសដ្យ។
console.log(cart[0]); // shoes
console.log(cart[1]); // shirt
console.log(cart[2]); // pants
console.log(cart.pop()); // pants
console.log(cart); // [ 'shoes', 'shirt' ]
console.log(cart.shift()); // shoes
console.log(cart); // [ 'shirt', 'pants' ]
cart.unshift("earrings");
console.log(cart); // [ 'earrings', 'shoes', 'shirt', 'pants' ]
៤.៣ Performance
រនុ្ចំសណ្ម្ methods ទំ្្បួនខា្ស ើ, methods push/pop ដំសណើរការស ឿន។ ចំស្នរឯ
methods shift/unshift ដំសណើរការយឺត។
ឧទហរណ៍៖
let cart = ["shoes", "shirt", "pants"];
cart.shift();
method shift ម្ិនក្តឹម្ស្ត ុបធាតុស្ដ សៅក្ត្់ index 0 សទ្ស្ងម្ទំ្្ក្តូវរំរិ ធាតុស្ដ សៅ
់ម្រខា្ស្ែ្សទ្ៀត។
shift operation ក្តូវសធែើបីដំណ្រ់កា ៖
1. ុបធាតុក្ត្់ index 0
2. រំរិ ធាតុស្ដ សៅ ់ម្រខា្ស្ែ្ និ្បតូរស ខ index ឱ្យក្តឹម្ក្តូវាម្ទ្ីាំ្្នីម្ួយៗ
3. Update array “cart” length
ឧទហរណ៍ pop ៖
let cart = ["shoes", "shirt", "pants"];
cart.pop();
console.log(arr1.length); // 4
console.log(arr1[0]); // undefined
console.log(arr1[1]); // undefined
console.log(arr1[2]); // undefined
console.log(arr1[3]); // undefined
console.log(matrix[0][0]); // 1
console.log(matrix[1][0]); // 4
console.log(matrix[2][0]); // 7
៤.៧ toString
សៅរនុ្ភាស្ JavaScript, សយើ្អាចបស្ម្ល្ array ឱ្យសៅជា string បានសដ្យសក្បើក្បា ់
method toString ។
let arr1 = [1, 2, 3, 4];
console.log(arr1); // [ 1, 2, 3, 4 ]
console.log(arr1.toString()); // 1,2,3,4
console.log(arr1.toString() == '1,2,3,4'); // true
arr1 = arr1.toString();
console.log(typeof arr1); // string
សៅសេ សយើ្សក្បើ square brackets ( [ ] ) ជាម្ួយនឹ្ unary + ទ្ធ្ គឺស មើនឹ្ string។
console.log([] + 1); // 1
console.log([1] + 1); // 11
console.log([1, 2] + 1); // 1, 21
លំហាត់
ចូរបស្កើត JavaScript function ស្ដ មាន parameter ម្ួយស្ដ តដម្លរប ់ parameter
សនាេះគឺជា array ដន integer។ សៅរនុ្ function សនាេះសយើ្សធែើការ loop ធាតុនីម្ួយៗស្ដ មាន
សៅរនុ្ array បនាទ្ប់ម្របូរបញ្េូ គាន្, ចុ្សក្កាយ returns ទ្ធ្ ស្ដ បានេី្ បូរសនាេះ។
ឧទហរណ៍៖
let arrayOfNumbers = [1, 8, 29, 2, -4];
sum(arrayOfNumbers); // 36
៥. Array methods
សដ្យស្រស្តសៅរនុ្ភាស្ JavaScript មាន array methods សក្ចើនដូចសនេះសៅរនុ្សម្សរៀន
សនេះសយើ្នឹ្ស្ប្ស្ចរវាជាបីចំនុចធំៗ។
ឧទហរណ៍ទ្ី២៖
let fruits = ["apple", "banana", "grape", "pineapple"];
o បស្នែម្ Add
ឧទហរណ៍ទ្ី១៖
let fruits = ["apple", "banana", "grape"];
ឧទហរណ៍ទ្ី២៖
let fruits = ["apple", "banana", "grape"];
o ជំនួ ( Replace )
ឧទហរណ៍ទ្ី១៖
let fruits = ["apple", "banana", "grape"];
ឧទហរណ៍ទ្ី១៖
let fruits = ["apple", "banana", "grape"];
• slice គឺជា method ស្ដ returns array ងមីស្ដ បានម្រេីការចម្ល្េី start ដ ់ end (
បុស្នតម្ិនរាប់បញ្េូ ទំ្ end សទ្ )។
Syntax រប ់ slice៖
arr.slice([start], [end]);
ឧទហរណ៍ទ្ី១៖
let fruits = ["apple", "banana", "grape"];
let copyFruits = fruits.slice(0, 2);
ឧទហរណ៍ទ្ី២ សដ្យគា្ន
្ end ៖
let fruits = ["apple", "banana", "grape"];
let copyFruits = fruits.slice(0);
ឧទហរណ៍ទ្ី៣ សដ្យគា្ន
្ start និ្ end ៖
let fruits = ["apple", "banana", "grape"];
let copyFruits = fruits.slice();
ឧទហរណ៍ទ្ី១៖
let num1 = [10, 20];
let num2 = [30, 40];
let num3 = num1.concat(num2, 5);
ឧទហរណ៍ទ្ី២៖
let num = [1, 2].concat([3, 4, 5]);
ឧទហរណ៍៖
let sizes = [28, 29, 30, 31, 32, 33];
sizes.forEach(function(ele, i, arr) {
console.log(`Element(${ele}) at Index(${i}) of array sizes (${arr})`);
// Element(28) at Index(0) of array sizes [28,29,30,31,32,33]
// Element(29) at Index(1) of array sizes [28,29,30,31,32,33]
// Element(30) at Index(2) of array sizes [28,29,30,31,32,33]
// Element(31) at Index(3) of array sizes [28,29,30,31,32,33]
// Element(32) at Index(4) of array sizes [28,29,30,31,32,33]
// Element(33) at Index(5) of array sizes [28,29,30,31,32,33]
});
ឧទហរណ៍៖
let user = { name: "Foo" };
let diverseData = ["hello", 20, false, user];
console.log(diverseData.indexOf("hello")); // 0
console.log(diverseData.indexOf("hello", 1)); // -1 because it starts from
// index 1
console.log(diverseData.lastIndexOf(user)); // 3
console.log(diverseData.lastIndexOf(user, diverseData.length - 2)); // -1
console.log(diverseData.includes(20)); // true
console.log(diverseData.includes(20, 2)); // false
ឧទហរណ៍ find ៖
let user = { name: "Foo" };
let diverseData = ["hello", 20, false, user];
Syntax រប ់ findIndex៖
arr.findIndex(function (element, index, array) {
// ...do something
});
ឧទហរណ៍ findIndex ៖
let user = { name: "Foo" };
let diverseData = ["hello", 20, false, user];
console.log(getIndex); // 2
• filter
console.log(evenNumber); // [ 2, 4, 6, 8, 10 ]
console.log(doubleEachElement); // [ 2, 4, 6, 8, 10 ]
console.log(doubleEachElement); // [ 2, 4, 6, 8, 10 ]
• sort()
Method sort គឺក្តូវបានសក្បើ ក្មាប់តសក្ម្ៀបធាតុាម្ ំដ្ប់សរើនឬងយ។
let num = [1, 2 , 15];
console.log(num.sort()); // [ 1, 15, 2 ]
ឧទហរណ៍ខា្ស ើបនាទ្បេ
់ ី sort សហើយសយើ្ស ើញថាស ខស្ដ ក្តូវាម្ ំដ្ប់
ស្ក្បសៅជាម្ិនក្តូវាម្ ំដ្ប់វិញ។ ម្ូ សហតុសដ្យស្រស្តសៅសេ សធែើការសក្បៀបសធៀប
sort បានបស្ម្ល្ធាតុទំ្្សនាេះសៅជា string, សហតុដច
ូ សនេះសហើយបានជា “2” > “15”។
console.log("2".codePointAt(0)); // 50
console.log("15".codePointAt(0)); // 49
console.log(num.sort(compare)); // [ 1, 2, 15 ]
• reverse()
Reverse បញ្ចញ្រ្ ំដ្ប់ចា ់។
ឧទហរណ៍៖
let num = [1, 2, 3, 4, 5];
console.log(num.reverse()); // [ 5, 4, 3, 2, 1 ]
console.log(num.join``); //1234
console.log(num.join("")); //1234
console.log(result); // 120
ដំសណើរការ៖
console.log(result1); // -13
console.log(result2); // -5
៥.៤ Array.isArray
សដ្យស្រស្តសៅរនុ្ភាស្ JavaScript, array, function, object ុទ្ធស្ត based on object
ទំ្្អ ់។ ដូចសនេះក្ប ិនសបើសយើ្សក្បើ typeof សដើម្្បីេិនិត្យសម្ើ ក្បសភទ្រប ់ array សនាេះ ទ្ធ្ គឺ
object។
let arr = [1, 2, 3, 4, 5];
console.log(Array.isArray(arr)); // true
console.log(Array.isArray(user)); // false
ស ចរតី ស្ខបរួម្៖
• សដើម្្បី add និ្ remove element៖
• push(...items) – បស្នែម្ items ខា្ចុ្ប្អ ់ដន array
• pop() – ុប item ខា្ចុ្ប្អ ់ដន array
• shift() – ុប item ខា្សដើម្ដំបូ្ដន array
• unshift(...items) – បស្នែម្ items ខា្សដើម្ដំបូ្ដន array
• splice(pos, deleteCount, ...items) – ក្ត្់ទ្ីា្
ំ រប ់ index, ុបចំនួនធាតុ
(items or elements), សហើយជំនួ សដ្យធាតុងមី
• slice(start, end) – បស្កើត array ងមីម្ួយសដ្យចម្ល្ធាតុរប ់ array សដើម្ាំ្្េី
start រហូតដ ់ end (ម្ិនរាប់បញ្េូ ទំ្្ end សទ្)
• concat(...items) – returns array ងមីម្ួយសដ្យចម្ល្ធាតុរប ់ array
ម្ួយឬរ៏សក្ចើន បញ្េូ គាន្និ្ទ្ិនន័យស្ដ ម្ិនស្ម្នជាធាតុរប ់ array
រ៏អាចរួម្បញ្េូ បានស្ដរ
• ចំនុចគួរយ ់ដឹ្ ៖
• Array.isArray(arr) េិនិត្យសម្ើ arr ជាក្បសភទ្ array ឬម្ិនស្ម្ន
• សៅសេ ស្ដ សយើ្សក្បើ methods sort, reverse និ្ splice, ទ្ក្ម្្់សដើម្ដន array
ក្តូវបានផ្ល្ ់បតូរ។
លំហាត់
ចូរបស្កើត JavaScript function ម្ួយសដើម្្បីតសក្ម្ៀបធាតុរប ់ array ាម្ ំដ្ប់សរើន
ឬងយអាក្ ័យស ើ parameter ទ្ី២, សបើ param ទ្ី២ ស មើនឹ្ “descending” ដ្
ំ ប់ដន array
ក្តូវតសក្ម្ៀបាម្ ំដ្ប់េីស ើចុេះសក្កាម្, សបើ param ទ្ី២ ស មើនឹ្ “ascending” ដ្
ំ ប់ដន array
ក្តូវតសក្ម្ៀបាម្ ំដ្ប់េីសក្កាម្ស ើ្ស ើ។
const nums = [ 43, 56, 23, 89, 88, 90, 99, 652];
៦. Destructuring Assignment
សៅរនុ្ភាស្ JavaScript, array និ្ object ជាក្បសភទ្ទ្ិននន័យស្ដ សយើ្ស ើញសគសក្បើក្បា ់
ញឹរញាប់ជា្សគ។ សេ ខលេះតដម្លរប ់ argument ស្ដ សយើ្សបាេះសៅឱ្យ function ាម្រយៈ
parameter ជាស្្នរម្ួយដន object ឬ array ស្តម្ិនស្ម្នជា object ឬ array ទំ្្ម្ូ សទ្។
Destructuring assignment គឺជា special syntax ស្ដ សយើ្អាចបស្ម្ល្ធាតុរប ់ object
និ្ array ជា ំណំអញ្ញតតិស្ដ សេ ខលេះវាមានភាេងាយក្ ួ ក្មាប់សយើ្យរសៅសធែើការស្្ស្ៗ។
ក្ប ិនសបើ function ម្ួយមាន params សក្ចើន ឬរ៏ params ទំ្្សនាេះមាន default values
សក្ចើនរសញរដញ, សយើ្អាចសក្បើ Destructuring សដើម្្បី ក្ម្ួ វាឱ្យមានងាយក្ ួ ។
console.log(apple); // apple
console.log(banana); // banana
console.log(mango); // mango
console.log(apple); // apple
console.log(mango); // mango
console.log(apple); // apple
console.log(banana); // banana
console.log(mango); // mango
console.log(num1); // 1
console.log(num3); // 3
console.log(num4); // 4
const books = ["Absalom, Absalom!", "A time to kill", "East of Eden", "The
sun also rises"];
const [title1, title2, ...titles] = books;
▪ Default values
ក្ប ិនសបើធាតុស្ដ សៅរនុ្ array តិចជា្អញ្ញតិតស្ដ សយើ្ច្់បានសនាេះេុំមាន error សទ្បុស្នត
តដម្លរប ់អញ្ញតតិសនាេះស មើនឹ្ undefined។
const [title1, title2 = "Pale fire", title3 = "Brave new world"] = books;
ឧទហរណ៍ទ្ី១៖
const user = {
firstname: "Joe",
lastname: "Biden"
};
const { lastname, firstname } = user;
const { a, b } = user;
console.log(a); // undefined
console.log(b); // undefined
console.log(firstname); // Joe
console.log(lastname); // Biden
ឧទហរណ៍ទ្ី២៖
const { title, author, published } = {
author: "Lois Lowry",
published: "May 2, 2011",
title: "Numbers the stars"
};
};
ងាយក្ ួ អានងាយក្ ួ យ ់៖
const options = {
base: 8,
};
លំហាត់
ចូរបស្កើត JavaScript function ស្ដ មានសឈា្្េះថា restResluts និ្មាន parameter ម្ួយ
សហើយ argument ស្ដ សបាេះសៅឱ្យ param សនាេះក្តូវស្តជា array ។ បនាទ្បម្
់ រសៅរនុ្ restResults
ក្តូវ return object ម្ួយ, ស្ដ properties សៅរនុ្ object សនាេះមានដូចជា៖
o property ដំបូ្គឺជាធាតុដំបូ្រប ់ array
o property ទ្ី២គឺជាធាតុទ្ី២រប ់ array
o property ទ្ី៣គឺជាធាតុស្ដ សៅស ់ទំ្្អ ់រប ់ array
• new Date(milliseconds)
const date = new Date(0);
console.log(date); // 1970-01-01T00:00:00.000Z
សៅសេ ស្ដ សយើ្បស្កើត Date សហើយសបាេះស ខ 0 ចូ , សនាេះគឺស មើនឹ្កា បរិសចេទ្
ដងៃទ្ី 1 ស្ខម្ររា ឆន្ំ 1970 ជាសេ សវលាចាប់ស្តើម្ ក្មាប់ Unix computer ឬរ៏ Unix
epoch។ ម្្ា្្សទ្ៀតស ខស្ដ តំណ្្ឱ្យ milliseconds ស្ដ សបាេះចូ សៅរនុ្
វ្់ក្រចររប ់ Date ក្តូវបានសគសៅថា timestamp ាំ្េីសេ សនាេះម្រ។
const aDayBefore = -24 * 3600 * 1000;
const date = new Date(aDayBefore);
console.log(date); // 1969-12-31T00:00:00.000Z
• new Date(dateString)
const date = new Date("2019-12-12");
console.log(date); // 2019-12-12T00:00:00.000Z
console.log(date); // 2002-09-11T00:00:00.000Z
console.log(date1); // 2002-09-11T00:00:00.000Z
សដ្យស្រស្តការបងាហ្ញសមា្្សៅស ើមា្ ុីនរុំេ្យួទ្័រនិ្ IDE ខុ គានៗ
្ បានជាសយើ្
ទ្ទ្ួ បាន ទ្ធ្ “2002-09-11” ស្ដ ជាការេិតវាក្តូវ “20002-09-12”។
console.log(date.getFullYear()); // 2002
console.log(date.getMonth()); // 8
console.log(date.getDate()); // 12
console.log(date.getDay()); // 6
console.log(date.getTime()); // 1034355600000
console.log(date.getHours()); // 7
console.log(date.getMinutes()); // 32
console.log(date.getSeconds()); // 20
console.log(date.getMilliseconds()); // 0
console.log(event.setFullYear(1969)); // -31536000000
console.log(event); // 1969-01-01T00:00:00.000Z
• setMonth(month, [date])
const event = new Date(0);
console.log(event); // 1970-01-01T00:00:00.000Z
console.log(event.setMonth(2)); // 5097600000
console.log(event); // 1970-03-01T00:00:00.000Z
• setDate(date)
const event = new Date(0);
console.log(event); // 1970-01-01T00:00:00.000Z
console.log(event.setDate(15)); // 1209600000
console.log(event); // 1970-01-15T00:00:00.000Z
console.log(event.setHours(6)); // -3600000
console.log(event); // 1969-12-31T23:00:00.000Z
console.log(event.setMinutes(30)); // 1800000
console.log(event); // 1970-01-01T00:30:00.000Z
• setSeconds(sec, [ms])
const event = new Date(0);
console.log(event); // 1970-01-01T00:00:00.000Z
• setMilliseconds(ms)
const event = new Date(0);
console.log(event); // 1970-01-01T00:00:00.000Z
console.log(event.setMilliseconds(500)); // 500
console.log(event); // 1970-01-01T00:00:00.500Z
• setTime(milliseconds)
console.log(event.setMilliseconds(500)); // 500
console.log(event); // 1970-01-01T00:00:00.500Z
• unary operator +
const now = new Date();
console.log(+now); // 1635416813610
៧.៥ Date.now()
Date.now() គឺដូចសៅនឹ្ new Date().getTime() ស្ដរបុស្នតវាខលីជា្។ ម្ិនស្តបុសណ្្្េះ
ដំសណើរការដ្ទខា្រនុ្រប ់វារ៏ស ឿនជា្ស្ដរ, េីសក្ េះវាម្ិនចាំបាច់បស្កើត Date object សទ្។
សហើយជាទ្ូសៅសបើសគ រស រសហគម្ ឬបស្កើតរម្មវិធីអែីម្ួយ សហើយសគសផ្្្តស ើ performance,
Date.now() គឺក្តូវបានសក្បើសក្ចើនបំ្ុត។
const now = new Date();
console.log(now.getTime()); // 1635417456100
console.log(Date.now()); // 1635417456100
៨.JSON methods
JSON ( JavaScript Object Notation ) គឺជាទ្ក្ម្្់ម្ួយស្ដ តំណ្្ឱ្យតដម្ល (ទ្ិននន័យ)។
សយើ្សក្បើ JSON សដើម្្បីផ្ល្ ់បតូរទ្ិននន័យាម្ទ្ក្ម្្់ម្ួយស្ដ ទំ្្ Client-side (JavaScript) និ្
Server-side ( C#, PHP, NODEJS, RUBY, JAVA … ) អាចយ ់បាន។
អនរ រស ររូដស្ត្ស្តឱ្យនិយម្ន័យខលីម្ួយ ក្មាប់ JSON គឺ data exchange format។
ឧទហរណ៍ទ្ី១៖
let product = {
name: "iphone13pro",
price: 1600,
color: "blue",
};
៨.១ JSON.stringify
Method រប ់ JSON មានេីរគឺ៖
• JSON.stringify ក្មាប់បស្ម្ល្ object សៅជាទ្ក្ម្្់ JSON
• JSON.parse ក្មាប់បស្ម្ល្ JSON ម្រ object វិញ។
ចំណ្ំ្៖
• ទ្ក្ម្្់ object
{
name: "iphone13pro",
}
ឧទហរណ៍៖
alert(JSON.stringify(false)); // false
alert(JSON.stringify("flower")); // "flower"
alert(JSON.stringify(10 + 20)); // 30
alert(JSON.stringify(product)); // {"name":"T-Shirt","price":20,"qty":2}
សទេះបីជា stringify យ
អ ្្ណ្រ៏វាមានស្ដនរំណត់ស្ដរ, ក្តូវក្បារដថា object ម្ិនមាន
circular references សៅសេ សក្បើជាម្ួយ stringify, សបើម្ិនដូសចនេះសទ្នឹ្បស្កើតជា error។
ឧទហរណ៍៖
const clothes = {
id: "0001",
createdAt: "Jul 10, 2021"
};
const shirt = {
color: "white"
};
៨.២ JSON.parse
សដើម្្បប
ី តូរទ្ិននន័យេី JSON ម្រ object វិញសយើ្សក្បើក្បា ់ JSON.parse។
ទ្ក្ម្្់រប ់ JSON.parse ៖
JSON.parse(str, [, reviver])
• str គឺជា json string ស្ដ ក្តូវបស្ម្ល្
• reviver គឺជា function ស្ដ ក្តូវបានសៅរា ់ key/value pair សហើយសយើ្អាច
សធែើការបស្ម្ល្ value ទំ្្សនាេះបាន
alert(afterParse.one); // 1
alert(afterParse.two); // 2
alert(afterParse.three); // 3
ឧទហរណ៍ជាម្ួយ param ទំ្្េីរ៖
const json = '{"one": 1, "two": 2, "three": 3}';
alert(doubleAfterParse.one); // 2
alert(doubleAfterParse.two); // 4
alert(doubleAfterParse.three); // 6
ស ចរតី ស្ខបរួម្៖
• JSON គឺជា data format exchange ស្ដ វាជា independent standard
language និ្អាចឱ្យភាស្ស្្ស្សទ្ៀតអាចសក្បើជាម្ួយវាបាន។
• JSON supports objects, arrays, strings, numbers, Booleans, និ្ null។
• JSON មានេីរ methods៖ JSON.stringify និ្ JSON.parse។
១. Recursion
Recursion គឺជា programming pattern ស្ដ ក្តូវបានសក្បើសៅសេ ស្ដ ការងារម្ួយគួរ
ស្តបំស្បរជាស្្នរតូចៗដូចគាន្សដើម្្បីងាយក្ ួ រនុ្ការសដ្េះក្ស្យបញ្ហ្។ សយើ្អាចសក្បើ recursive
function សដើម្្បីសដ្េះក្ស្យការងារជារ់លារ់ណ្ម្ួយសៅរនុ្ data structures បាន្្ស្ដរ។
សៅសេ ស្ដ function សដ្េះក្ស្យបញ្ហ្ម្ួយ សហើយសៅរនុ្ដំសណើរការរប ់វាអាច call
សៅខលួនវាបានសក្ចើនដ្, function សនាេះក្តូវបានសគសៅថា recursion។
return result;
};
console.log(pow(2, 3)); // 8
console.log(pow(3, 3)); // 27
o សក្បើក្បា ់ recursion
const pow = (x, n) => {
if (n == 0) {
return 1;
}
console.log(pow(2, 3)); // 8
console.log(pow(3, 3)); // 27
console.log(pow(4, 2)); // 16
development: {
sites: [{
name: 'Peter',
salary: 2000
}, {
name: 'Alex',
salary: 1800
}],
internals: [{
name: 'Jack',
salary: 1300
}]
}
};
ក្ប ិនសបើសយើ្សក្បើ for loop សដើម្្បី loop ស ើ properties រប ់ company ដូចជា sales និ្
development ។ បុស្នតសៅរនុ្ development មាន properties ស្្ស្សទ្ៀតស្ដ តដម្លរប ់េួរវាជា
array ដូចសនេះសយើ្ក្តូវសក្បើក្បា ់ for loop ម្ួយរក្ម្ិត (ឬ រ្យម្ិន្លូវការបុស្នតក្ ួ ស្្្ប់គឺម្ួយត្់)
សទ្ៀត, ដូចសនេះសយើ្ក្តូវសក្បើ loop េីរត្់ ក្ប ិនសបើដងៃម្ុខមាន sub loop ម្ួយត្់ឬេីរត្់សទ្ៀតសៅរនុ្
properties ទំ្្សនាេះអ៊ីចឹ្សយើ្ក្តូវសក្បើក្បា ់ loop បីឬបួនត្់សដើម្្បីររក្បារ់ស្ខ រុបរប ់បុគគ ិរ
ទំ្្អ ់។ កា ណ្សយើ្សក្បើក្បា ់ loop ចាប់េី 3ត្់ស ើ្សៅវានឹ្បស្កើតជាភាេ មុគស្្្ញស្ដ
អនរ រស ររូដស្ត្ស្តសជៀ វា្ ដូចសនេះបានជាសគបស្កើត recursive traversals ម្រសដើម្្បី ក្ម្ួ េី
ការងារ មុគស្្្ញឱ្យមានភាេងាយក្ ួ ។
return sum;
}
};
console.log(totalSalaries(company)); // 2500
លំហាត់
ឧទហរណ៍ទ្ី២៖
const displayFruits = (mango, ...fruits) => {
console.log(mango); // Mango
console.log(arguments.length); // 3
ចំណ្ំ៖ សយើ្សក្បើ special array-like object arguments បានស្តសៅរនុ្ regular functions សទ្,
ម្ិនអាចសក្បើវាសៅរនុ្ arrow functions បានសទ្េីសក្ េះ arrow functions អត់មាន arguments
និ្ this សទ្។
▪ Spread syntax
console.log(Math.max(num1)); // NaN
console.log(Math.max(num1[0], num1[1], num1[2])); // 8
console.log(Math.max(...num1)); // 8
console.log(Math.min(...num1)); // -9
ក្មាប់និម្ិតតិ ញ្ញ្ spread syntax ដូចសៅនឹ្ rest parameter ស្ដរ, បុស្នតម្ុខងាររប ់េួរវា
គឺបញ្ចញ្រ្ គាន្។ spread syntax សយើ្សក្បើ ក្មាប់បស្ម្ល្ array សៅជា list of arguments ចំស្នរឯ
rest parameter សយើ្សក្បើ ក្មាប់ទ្ទ្ួ យរ list of arguments សៅជា array វិញ។
• ( ... ) ក្ប ិនសបើវាសៅរនុ្ parameter រប ់ function វាជា rest parameter
• ( ... ) ក្ប ិនសបើវាសៅរនុ្ function call វាជា spread syntax
logUserInfo(...users);
លំហាត់
ចូរបស្កើត function ម្ួយស្ដ មានសឈា្្េះថា filterOutOdds ស្ដ function សនេះមានម្ុខងារ
ក្មាប់សក្ចាេះយរស្តស ខគូបុសណ្្្េះសដ្យសក្បើក្បា ់ array ដូចខា្សក្កាម្។ ម្ុននឹ្សបាេះ array
សនេះសៅឱ្យ filterOutOdds ក្តូវស្តបស្ម្ល្វាសៅជា spread syntax ិន។ ចំស្នរឯ parameter
ស្ដ ចាំទ្ទ្ួ តដម្លក្តូវស្តជា rest parameters។ បនាទ្ប់ម្រសៅរនុ្ filterOutOdds សធែើការបងាហញ
្
ស ខគូទំ្្សនាេះសៅស ើផ្្
ទ្ំ console បនាទ្ប់េីសក្ចាេះរួច។
const arrayOfNums = [1, 2, 22, 31, 3, 5, 8, 7, 90, 82];
៣. Variable scope
JavaScript គឺជា function-oriented language, មានន័យថា function អាចបស្កើតសេ
ណ្រ៏បាន, អាចសធែើជា argument ក្មាប់សបាេះឱ្យ functions ស្្ស្សទ្ៀតរ៏បាន, និ្អាចសៅសក្បើ
សៅសេ សក្កាយេីរស្នល្ស្្ស្បាន្្ស្ដរ។ សយើ្រ៏បានសរៀនរួចសហើយស្ដរ, function អាច access
អញ្ញតតិស្ដ សៅខា្សក្ៅ scope រប ់វាសហើយស្ងម្ទំ្្អាចស្រស្ក្បអញ្ញតតិទំ្្សនាេះបានសទ្ៀត្្។
ម្្ា្្វិញសទ្ៀតសៅរនុ្ function រ៏មាន scope រប វា
់ ស្ដរ។
ឧទហរណ៍ទ្ី១៖
const a = 20;
console.log(a); // 20
{
const b = 10; // អាចសក្បើបានស្តរន្
ុ block code { ... } សនេះសទ្
console.log(b); // 20
}
{
const a = 10; // អញ្ញតតិ a រនុ្សនេះ និ្ អញ្ញតតិ a សៅខា្សក្ៅគឺម្ិន រ់េន
័ ធគាន្សទ្
console.log(a); // 10
}
អញ្ញតតិស្ដ សៅរនុ្ block រប ់ if, else if, loop ។ ។ ដូចសៅនឹ្ block code ស្ដ គឺម្ិន
អាចសៅសក្បើសៅខា្សក្ៅ block រប ់វាបានសទ្។
for (let i = 0; i < 5; i++) {
let sum = 0;
sum += i;
}
console.log(sum()); // 30
}
displayResult();
ឧទហរណ៍ទ្ី២៖
function incrementByOne() {
let count = 1;
console.log(counter()); // 1
console.log(counter()); // 2
console.log(counter()); // 3
console.log(cat); //Micky
console.log(j); // 1
console.log(i); // 5
console.log(j); // 1
console.log(i); // 5
ក្ប ិនសបើមាន block code សៅរនុ្ function សហើយ var ែិតសៅរនុ្ block សនាេះ, អ៊ីចឹ្ var
គឺជា function-level រប ់ function សនាេះ, មានន័យថាអាចសក្បើក្បា វា
់ បានស្តរនុ្ function
សនាេះបុសណ្្្េះ៖
function sum() {
{
var b = 4;
}
console.log(b); // 4
}
sum();
console.log(b); // ReferenceError: b is not defined
console.log(season); // rainy
ឧទហរណ៍ទ្ី២៖
let season = "dry";
let season = "rainy";
ស្ខបស ចរតីរួម្៖
• var គា្្ន block scope សទ្
• ការក្បកា អញ្ញតតិសដ្យសក្បើក្បា ់ var, អញ្ញតតិសនាេះគឺ hoisted ( ក្តូវបានរំរិ សៅ
ខា្សដើម្ប្អ ់រប ់ script ឬ function )
• const និ្ let ខុ េី var ក្ត្់េីរចំនុចធំៗខា្ស ើសនេះ
var a = 10;
}
sum();
var a = 10;
}
sum();
ដូចសៅនឹ្៖
var a;
a = 10;
console.log(a); // 10
a = 10;
console.log(a); // ReferenceError: a is not defined
៥. Global object
Global object ្ត ់ឱ្យសយើ្នូវអញ្ញតតិ និ្ functions ជាសក្ចើនស្ដ អាចសក្បើសៅក្គប់រស្នល្
សដ្យអាក្ យ
័ សៅស ើ environment ( environment មានដូចជា browser, Nodejs … )។
សៅស ើ browser, global object មានសឈា្្េះថា window និ្សៅស ើ Nodejs វាមានសឈា្្េះ
ថា global, វាអាចនឹ្មានសឈា្្េះស្្ស្សទ្ៀតសៅាម្ environment នីម្ួយៗ។
ងមីៗសនេះ, globalThis ក្តូវបានបញ្េូ សៅរនុ្ភាស្ JavaScript សហើយសយើ្អាចសក្បើ global
object ត្់ដ្រម្ួយសនេះសៅក្គប់ environments ទំ្អ ់ ជាេិស វា support browser
ំខាន់ៗទំ្្អ ់ដូចជា Chrome, Firefox, Safari ។ ។ បុស្នតសៅរនុ្ចំនុចសនេះសយើ្នឹ្ស ើរយរ
ស្ត window ម្រនិយយស្តបុសណ្្្េះ។ សយើ្បានសក្បើសក្ចើនម្រសហើយដូចជា console.log, alert
។ ។ ទំ្អ ់សនេះ ុទ្ធជា method រប ់ window។
ឧទហរណ៍៖
// ដូចគាន្
window.console.log("Hello JavaScript!");
console.log("Hello JavaScript!")
// ដូចគាន្
window.alert("Hello JavaScript");
alert("Hello JavaScript");
// ដូចគាន្
window.prompt("Enter something");
prompt("Enter something");
console.log(window.num); // 5
console.log(window.str); // undefined
console.log(window.id); // undefined
console.log(sum(2, 3)); // 5
console.log(window.sum(2, 3)); // 5
console.log(multiple(3, 4)); // 12
console.log(window.product.price); // 1000
ស្ខបស ចរតីរួម្៖
• Global object មាន properties ជាសក្ចើនស្ដ សយើ្អាច access ម្រសក្បើសៅរស្នល្ណ្
រ៏បានដូចជា window.innerWidth ( ក្មាប់សម្ើ េីទ្ំហំទ្ទ្ឹ្សៅស ើ browser )
• Global object មានសឈា្្េះសៅាម្ environment នីម្ួយៗដូចជា browser (
window), Nodejs (global) និ្សឈា្្េះរួម្ (globalThis)
• ក្ប ិនជាសយើ្ច្់បស្កើតអញ្ញតតិម្ួយស្ដ អាចសក្បើបានក្គប់រស្នល្ សៅរនុ្ project
ទំ្្ម្ូ , សយើ្គួរបស្កើតវាសដ្យសក្បើក្បា ់ global object
• អញ្ញតតិស្ដ បស្កើតសដ្យសក្បើក្បា ់ let, const, រួម្ទំ្្ function expressions ម្ិនស្ម្ន
ជា properties រប ់ global object សទ្។
ឧទហរណ៍សដ្យមាន arguments ៖
setTimeout((a, b) => {
console.log(a + b); // 20 after 1s
ឧទហរណ៍សដ្យម្ិនមាន arguments ៖
setTimeout(() => {
console.log("Hello, I'm setTimeout."); // Hello, I'm setTimeout.
}, 1000);
ឧទហរណ៍៖
const timerId = setTimeout(greetings, 1000);
console.log(timerId); // 1
clearTimeout(timerId);
៦.៣ setInterval
Syntax ៖
const timerId = setInterval(func, [delay], [arg1], [arg2], ...);
ឧទហរណ៍៖
setInterval(greetings, 1000);
console.log(timerId); // 1
clearInterval(timerId);
setTimeout(() => {
clearInterval(timerId);
}, 8000);
សៅសេ ស្ដ engine ដំសណើរការម្រដ ់ជួរ // * វាបានដ្រ់ function call ស្ដ សៅរនុ្
setTimeout សៅរនុ្ calender បនាទ្ប់ម្រវាដំសណើរការជួរបនាទ្ប់ // ** សហើយបងាហ្ញ ទ្ធ្ “I'm
going to run before setTimeout.” សៅស ើផ្ទ្ំ្ console បនាទ្ប់ម្រសទ្ៀត engine
ដឹ្ថាគា្្នអែីក្តូវដំសណើរការសទ្ៀត (សដ្យស្រជួរ // ** គឺជាជួរចុ្សក្កាយប្អ ់សៅរនុ្ script)
វារ៏ទញ function call េីរនុ្ calender (សក្កាយ ០ms) ម្រវិញសហើយដំសណើរការ function
សនាេះ។ ដូចសនេះសហើយបានជាសយើ្ស ើញថា “I'm going to run before setTimeout.” បងាហ្ញម្ុន
“I will run after current script finished.”។
ស ចរតី ស្ខបរួម្៖
• setTimeout អាចឱ្យសយើ្ដំសណើរការ function ម្ត្បនាទ្ប់េីចសនាល្េះសេ ម្ួយ
• setInterval អាចឱ្យសយើ្ដំសណើរការ function ម្ត្បនាទ្ប់េីចសនាល្េះសេ ម្ួយ
សហើយបនតដំសណើរការស្បបសនេះរហូតសរៀ្រា ់ delay ម្ត្
• សដើម្្បីបញ្្ឈប់ដំសណើរការេួរវា, សយើ្សក្បើ clearTimeout និ្ clearInterval សដ្យ
សបាេះ timerId រប ់េួរវាសៅឱ្យ methods ទំ្្េីរសនេះ
• Zero (0) delay scheduling សក្បើជាម្ួយ setTimeout, គឺក្តូវបាន schedule call
បនាទ្ប់េី current script ក្តូវបានបញ្េប់
លំហាត់
ចូរបងាហ្ញដងៃស្ខ និ្ឆន្ំបចេុប្បននសរៀ្រា ់ម្ួយវិនាទ្ីម្ត្ និ្ក្តូវឈប់បងាហ្ញបនាទ្ប់េី ដប់វិនាទ្ីក្តូវ
បានរនល្ហួ សៅ។ គនលឹេះ៖ សក្បើក្បា ់ setTimeout, setInterval និ្ Date object។
function calcOutcome(func) {
const result = func(5); // **
return result;
}
console.log(item.totalPrice(2)); // 20
៧.១ bind()
សយើ្បានដឹ្ឧទហរណ៍អំេីការបាត់ប្់ “this” keyword សហើយ, ឥ ូវសយើ្ម្រសម្ើ េីរសបៀប
ដនការសដ្េះក្ស្យបញ្ហ្សនេះសដ្យសក្បើក្បា ់ bind។
ឧទហរណ៍ខា្ស ើដស្ដ ៖
const item = {
getOriginalPrice() {
return 10;
},
totalPrice(qty) {
return this.getOriginalPrice() * qty; // *
}
}
function calcOutcome(func) {
const result = func(5); // **
return result;
}
console.log(item.totalPrice(2)); // 20
console.log(calcOutcome(item.totalPrice.bind(item))); // 50
ឧទហរណ៍ទ្ី២៖
const user = {
name: "Tida"
};
const otherUser = {
name: "Seyha"
};
function greetings() {
console.log(`Hello sir, I'm ${this.name}`)
}
ឧទហរណ៍ខា្ស ើសនេះតដម្លរប ់ “this” អាក្ ័យស ើ function ស្ដ វា ែិតសៅ, ស្ដ bind
ជាម្ួយ object ណ្ម្ួយ។
ឧទហរណ៍ទ្ី៣៖
console.log(sumWithFive(1)); // 6
console.log(sumWithFive(2)); // 7
console.log(sumWithFive(3)); // 8
ឧទហរណ៍ទ្ី២៖
const numbers = [5, 6, 2, 3, 7];
console.log(maxApply); // 7
console.log(maxCall); // 7
console.log(minApply); // 2
console.log(minCall); // 2
សៅសេ ស្ដ សយើ្ម្ិនបាន reference សៅកាន់ object ណ្ម្ួយសៅសេ សក្បើក្បា ់ call និ្
apply, context ស្ដ ជា parameter ដំបូ្រប ់វាគួរស្តសក្បើតដម្លជា null ។
ឧទហរណ៍ទ្ី៣៖
const user1 = {
name: "Nita",
age: 20,
gender: "female",
displayInfo() {
console.log(`
Name: ${this.name}
Age: ${this.age}
gender: ${this.gender}
`)
}
};
const user2 = {
name: "Tola",
age: 18,
gender: "male",
};
const user3 = {
name: "Mina",
age: 21,
gender: "female",
};
user1.displayInfo.apply(user2, Object.values(user2));
/*
Name: Tola
Age: 18
gender: male
*/
user1.displayInfo.call(user3, user3);
/*
Name: Mina
Age: 21
gender: female
*
ភាេខុ គាន្រវា្ bind និ្ call/apply គឺ bind return function ងមីម្ួយស្ដ នឹ្ក្តូវ call
សៅសក្បើសៅសេ សក្កាយ ចំស្នរឯ call/apply ដំសណើរការ function ភាល្ម្ៗ។
លំហាត់
ជំនួ សដ្យ៖
const displayElement = (ele) => {// we called it “helper function”
console.log(ele);
}
[1, 2, 3, 4].forEach(displayElement); // 1, 2, 3, 4
[5, 6, 7, 8].forEach(displayElement); // 5, 6, 7, 8
ឧទហរណ៍ទ្ី១៖
const displayName = () => {
console.log(this); //undefined
};
displayName();
ឧទហរណ៍ទ្ី២៖
const user = {
firstname: "Jack",
lastname: "Ma",
age: 53,
displayInfo() {
const fullname = () => {
// this was taken from its outer scope(displayInfo)
return this.firstname + " " + this.lastname;
};
user.displayInfo();
ឧទហរណ៍ខា្ស ើសៅរន្
ុ regular function “fullname”, “this” ស មើនឹ្ undefined
សៅរនុ្ “strict mode” សបើម្ន
ិ ែិតសៅរនុ្ strict mode សទ្គឺ “this” ស មើន្
ឹ window ។
ចំណ្ំ៖ arrow function ម្ិនអាចសក្បើជាម្ួយ constructor “new” ដូច regular function
បានសទ្។ ម្្ា្្សទ្ៀតការសក្បើក្បា ់ bind ជាម្ួយ arrow function រ៏ម្ិនខុ េីសក្បើក្បា ់ “this”
សៅរនុ្ arrow function ស្ដរគឺវាសៅស្ ែ្ររ “this” សៅ outer scope រប ់វា។
មម្មរៀនទី៧ Classes
constructor() ក្តូវបានសៅសដ្យ យ
ែ័ ក្បវតតិសដ្យ operator “new”, ដូចសនេះសយើ្អាច
ក្បកា state ( member variables ) សៅទ្ីសនេះ។
ឧទហរណ៍៖
class Cat {
constructor() {
this.purr = "meow meow";
}
getPurr() {
console.log(this.purr);
}
}
1. object ងមីម្ួយក្តូវបានបស្កើត
2. constructor ចាប់ស្តើម្ដំសណើរការ បនាទ្ប់ម្រអញ្ញតតិ “purr” ក្តូវបានបស្កើត និ្ក្តូវបាន
្ត ់តដម្ល “meow meow”
3. បនាទ្ប់ម្រសយើ្ assign object ងមីសនាេះសៅឱ្យអញ្ញតតិ “micky” និ្ call សៅ method
“getPurr”។
ចំណ្ំ៖ method នីម្ួយៗសៅរនុ្ class ម្ិនក្តូវបានខណឌស្ចរសដ្យ comma “ , ” ដូចសៅរនុ្
object សទ្។
getPurr() {
console.log(this.purr);
}
}
get name() {
return this._name;
}
set name(newName) {
this._name = newName;
}
}
cat.name = "Tommy";
console.log(cat.name); // Tommy
["get" + "fullname"]() {
return this.firstname + " " + this.lastname;
}
}
displayFullname() {
console.log(this.firstname + " " + this.lastname);
}
}
សដើម្្បីសដ្េះក្ស្យបញ្ហ្សនេះសយើ្មានេីររសបៀប៖
1. សក្បើក្បា ់ function ជំនយ
ួ
setTimeout(() => {
user.displayFullname();
}, 500); // Dy Channa
2. សក្បើក្បា ់ bind
setTimeout(user.displayFullname.bind(user), 500); // Dy Channa
លំហាត់
ចូរ រស ររូដខា្សក្កាម្ម្ត្សទ្ៀតសដ្យបតូរេី function constructor “new” សៅជា class។
function Book (title, author, publishedAt) {
this.title = title;
this.author = author;
this.publishedAt = publishedAt;
}
២. Class inheritance
Class inheritance គឺជារសបៀបស្ដ class ម្ួយទ្ទ្ួ ម្រតរេីខលេះម្ួយស្្ស្សទ្ៀត។
ម្រតរសៅក្ត្់ចំនុចសនេះគឺនិយយអំេី ( variables និ្ methods ស្ដ parent class មាន )។
isInStock() {
if (this.status == "in stock") {
console.log(`${this.name} is ${this.status}`);
} else {
console.log(`${this.name} is ${this.status}`);
}
}
}
Object “shoes” អាច access បានទំ្្ methods រប ់ class Shoes “total” និ្ method
រប ់ class Product “isInStock” ។ ចំស្នរឯដំសណើរការដ្ទខា្រនុ្, “extends” keyword សធែើការ
សដ្យសក្បើវិធីស្ញ្ច ត “prototype mechanism”។ វាសធែើការ set “Shoes.prototype.[[Prototype]]
សៅឱ្យ Product.prototype, ដូចសនេះក្ប ិនសបើ method ម្ិនក្តូវបានររស ើញសៅរនុ្
Shoes.prototype សទ្, សនាេះវានឹ្សៅយរេី Product.prototype។ ដូចជាសយើ្បានស ើញសហើយ
method “isInStock” គឺក្តូវបានយរម្រេី Product.prototype។
សដើម្្បីស្ ែ្ររ method “ isInStock ”, JavaScript engine ក្តូវសធែើការេីសក្កាម្ស ើ្ស ើ
( ក្មាប់រូបភាេខា្ស ើ)៖
• Object “shoes” អត់មាន method “isInStock” សទ្
• វាសៅររសៅរនុ្ prototype រប ់វា (Shoes.prototype), prototype រប ់វារ៏អត់មានស្ដរ
• Prototype រប ់វាបាន “extends” េី Product.prototype, ដូចសនេះវាអាចសៅររេី
Product.prototype ស្ដ ជារស្នល្ស្ដ វាររស ើញនូវ method សនាេះ។
isInStock() {
if (this.status == "in stock") {
return true;
} else {
return false;
}
}
}
ចំណ្ំ្៖ Arrow functions អត់មាន “ super ” សទ្, សៅសេ ស្ដ សយើ្សក្បើ “ super ” វានឹ្
សៅររេី outer scope។ ឧទហរណ៍ថាសយើ្សក្បើ setTimout សៅរនុ្ method “ total ” ដូចខា្
សក្កាម្សនាេះ ទ្ធ្ នឹ្ទ្ទ្ួ បានដូចស្ដ បានរំេឹ្ទ្ុរេីសក្ េះ “ super ” ក្តូវបានយរម្រេី outer
scope រប ់វាក្ត្់ចំនុចសនេះគឺ total ៖
setTimeout(() => {
console.log(super.isInStock());
}, 500);
setTimeout(function() {
}, 500);
// ...
}
const boots = new Shoes("boots", 199, 1, 0, "out of stock");
console.log(boots); // SyntaxError: 'super' keyword unexpected here
រុបស ចរតីរួម្៖
• សដើម្្បី extend class សយើ្សក្បើក្បា ់ keyword “extends”
o ឧ.ទ្៖ class Child extends Parent
o ស្ដ Child.prototype.__proto__ គឺជា Parent.prototype
• សៅសេ ស្ដ សយើ្ override constructor៖
o សយើ្ក្តូវស្ត call សៅ parent constructor សដ្យសក្បើក្បា ់ super()
សៅរនុ្ child constructor ម្ុននឹ្សយើ្សក្បើក្បា ់ keyword “this”
• សៅសេ ស្ដ សយើ្ override method ស្្ស្សទ្ៀតរប ់ parent៖
o សយើ្អាចសក្បើក្បា ់ super.method() សៅរនុ្ child method សដើម្្បី call
សៅ method រប ់ parent class
• Arrow functions អត់មាន “this” និ្ “super” សទ្, ដូចសនេះេួរវាក្តូវបានយរេី
outer scope
ឧទហរណ៍ទ្ី២៖
class Product {}
Product.displayName = function () {
console.log(this === Product); // true
}
Product.displayName(); // true
ឧទហរណ៍៖
class Product {
constructor(name, price, color) {
this.name = name;
this.price = price;
this.color = color;
}
console.log(Product.name); // Addidas
console.log(Product.price); // 249
}
}
៤.១ Protecting
Protecting field ក្តូវបាន ំគា ់សដ្យ ញ្ញ្ underscore សៅខា្ម្ុខ field និ្ម្ិន ែិត
សៅរនុ្ constructor, បុស្នតវាម្ិនស្ម្នជាអែីស្ដ ភាស្ JavaScript តក្ម្ូវឱ្យសធែើស្បបសនេះសទ្ វាគឺជា
ភាេងាយក្ ួ រនុ្ការចំណ្ំស្ដ អនរ រស ររូដយ ់ក្ បគានថា
្ field ហនឹ្ម្ិនគួរ access
េីខា្សក្ៅ class បុស្នតអាច access េី child class ស្ដ បានទ្ទ្ួ ម្រតរេីវា។
ឧទហរណ៍៖
class Product {
_originalPrice = 20;
get originalPrice() {
return this._originalPrice;
}
set originalPrice(value) {
this._originalPrice = value;
}
}
item.originalPrice = 50;
console.log(item.originalPrice); // 50
៤.២ Read-only
Read only field គឺជា field ស្ដ ក្តូវបាន្ត ់តដម្លឱ្យសៅសេ ស្ដ សយើ្បស្កើត object
ស្តបុសណ្្្េះ និ្ម្ិនអាចផ្ល្ ់បតូរតដម្លរប ់វាបានសទ្ក្ប ិនសបើគា្ន method ជំនួយ។
ឧទហរណ៍ទ្ី១ សដ្យគា្ន
្ setter method៖
class Product {
constructor(value) {
// read-only field
this._readOnly = value;
}
get readOnly() {
return this._readOnly;
}
}
// error: Cannot set property readOnly of #<Product> which has only a getter
item.readOnly = 299;
get readOnly() {
return this._readOnly;
}
set readOnly(value) {
if (value < 0) {
value = 0;
}
this._readOnly = value;
}
}
item.readOnly = -299;
console.log(item.readOnly); // 0
item.readOnly = 359;
console.log(item.readOnly); // 359
៤.៣ Private
Private field ចាប់ស្តើម្សដ្យនិម្ិតត ញ្ញ្ hash (#) ស្ដ # តំណ្្ឱ្យ private field,
សហើយ field ម្ួយសនេះអាច access បាន ស្តសៅរន្
ុ class ស្តបុសណ្្្េះ។ ក្មាប់ការក្បកា រប ់វា
រ៏ដូចសៅនឹ្ protected field ស្ដរគឺសយើ្ក្បកា សៅខា្សក្ៅ constructor។
class Product {
// private field
#qty = 5;
get getQty() {
return this.#qty;
}
set getQty(value) {
this.#qty = value;
}
}
item.getQty = 200;
console.log(item.getQty); // 200
ស ចរតី ស្ខបរួម្៖
• Object fields ស្ប្ស្ចរជាេីរ៖ private និ្ public, ចំស្នរ protected ក្គាន់ស្តជា
ការ ំគា ់រប ់អនរ រស ររូដស្តបុសណ្្្េះ
• Protected និ្ read-only ស្តើម្សដ្យនិម្ិតត ញ្ញ្ underscore ( _ ) ដូចគាន,្ បុស្នត
protected ក្បកា សៅខា្សក្ៅ constructor, read-only ក្បកា សៅរនុ្
constructor
• Private ស្តើម្សដ្យនិម្ត
ិ ត ញ្ញ្ hash ( # ) ស្ដ field សនេះម្ិនអាច access
សៅខា្សក្ៅ class រប វា
់ បានសទ្
• សក្ៅេីអែីស្ដ បានសរៀបរាប់ខា្ស ើគឺជា public field
៥.១ instanceof
Syntax រប ់ instanceof៖ object_name instanceof class_name
ឧទហរណ៍ទ្ី១៖
class Apple {}
class Android {}
លំហាត់
ចូរបស្កើត class Car ម្ួយស្ដ មាន properties េីរគឺ (brand និ្ speed) និ្ methods
បី៖
1. accelerate ក្មាប់បស្កើន speed អាក្ យ
័ ស ើតដម្លរប ់ param ស្ដ សយើ្សបាេះាម្
method សនេះ
2. brake ក្មាប់បនែយ speed ស្ដ វាអាក្ ័យស ើតដម្លរប ់ param ដូចគាន្
a. និ្ចុ្សក្កាយគឺ method status ក្មាប់បងាហញ
្ េី brand និ្ speed (ឧ.ទ្
Prius is running at 80 kilometers per hour.)
ជំពូកទី៣ Advanced
} catch(err) {
...show err
}
ដំសណើរការរប ់វា៖
1. ដំបូ្ try { … } block ដំសណើរការ
2. ក្ប ិនសបើគា្ន error, catch block នឹ្ម្ិនក្តូវបានដំសណើរការសហើយវាបញ្េប់ដំសណើរការ
រប ់ try…catch block
3. បុស្នតខណៈសេ រំេុ្ដំសណើរការ try { … } block សហើយមាន error សនាេះវានឹ្បញ្េប់ try
block ភាល្ម្ៗក្ត្់ចំនុច error សហើយបនតសៅកាន់ catch block, បនាទ្ប់ម្រ catch block
ចាប់ស្តើម្ដំសណើរការរូដស្ដ មានសៅរនុ្ block រប ់វា សក្កាយម្របញ្េប់ try…catch។
ឧទហរណ៍ទ្ី១៖
try {
const a = 5;
const b = 8;
console.log(a + b); // 13
} catch(err) {
console.log("Catch block won't execute.");
}
សៅរនុ្ឧទហរណ៍ទ្ី១សនេះ ម្ិនមានរំហុ ្គ្អែីសទ្ដូចសនេះ catch block នឹ្ម្ិនក្តូវបាន
ដំសណើរការសទ្។
ឧទហរណ៍ទ្ី២៖
try {
const a = 5;
const b = 8;
b = 10; // *
console.log(a + b);
} catch(err) {
console.log("At this time, catch block executed");
}
ឧទហរណ៍៖
try {
const a = 5;
const b = 8;
b = 10; // *
console.log(a + b);
} catch(err) {
console.log(err.name); // TypeError
console.log(err.message); // Assignment to constant variable.
if (naturalNumber < 0 ) {
throw new Error("Number must be greater than zero."); // *
}
} catch(err) { // **
console.log(err.message); // ***
}
ឧទហរណ៍ខា្ស ើក្ប ន
ិ សបើសយើ្បញ្េូ ស ខស្ដ តូចជា្ 0 សនាេះក្ត្់ជួរ // * នឹ្ដំសណើរ
ការ សហើយបញ្ជូន constructor error ម្រកាន់ parameter “err” ក្ត្់ជួរ // ** និ្សធែើការបងាហ្ញ
រ្យ "Number must be greater than zero." ក្ត្់ជួរ // *** ។
ឧទហរណ៍ទ្ី២៖
try {
let price = prompt("Enter price: ");
let discount = .8;
} catch(err) {
console.log(err.name);
console.log(err.message);
}
១.៤ try…catch…finally
try…catch…finally មាន រខណៈខុ េី try…catch ក្ត្់ finally block ដំសណើរការរហូត
សទេះបីជាមាន error ឬម្ិនមាន error។
▪ try ដំសណើរការសៅសេ គា្ន
្ error
▪ catch ដំសណើរការសៅសេ ស្ដ មាន error
▪ finally ដំសណើរការរហូត
Syntax៖
try {
// ដំសណើរការសៅសេ គា្ន
្ error ...
} catch (err) {
// ដំសណើរការសៅសេ មាន error ...
} finally {
// ដំសណើរការរហូត ...
}
ឧទហរណ៍ទ្ី១៖
try {
console.log("try block executed."); // try block executed.
} catch(err) {
console.log("catch block executed.");
} finally {
console.log("finally block executed."); // finally block executed.
}
ឧទហរណ៍ទ្ី២៖
try {
throw new Error("pretend an error in try block!");
console.log("try block executed.");
} catch(err) {
console.log("catch block executed."); // catch block executed.
} finally {
console.log("finally block executed."); // finally block executed.
}
ឧទហរណ៍ទ្ី៣៖
let num1 = +prompt("Enter some numbers: ");
let result;
try {
result = isNatural(num1);
} catch(err) {
console.log(err.message)
} finally {
console.log(`${num1} is ${ result ? "a natural number." : "not a natural
number."}`)
}
function isNatural(num) {
if (!num) {
throw new Error('Not a number');
}
return (num >= 0.0) && (Math.floor(num) === num) && num !== Infinity;
}
ឧទហរណ៍ខា្ស ើសយើ្េិនិត្យការបញ្េូ រប ់ user ថាជា natural number ឬ រ៏ម្ិនស្ម្ន។
បុស្នតសទេះជា ទ្ធ្ យ្្ណ្រ៏សដ្យ សយើ្ស ញ
ើ ថា console.log សៅរនុ្ finally block ដំសណើរ
ការជានិចេ។ ដូចសនេះសៅសេ ស្ដ សយើ្ច្់បាន ទ្ធ្ ម្ួយសទេះបីជារូដរប ់សយើ្ដំសណើរការសជាគ
ជ័យ ឬអត់រ៏សដ្យសយើ្គួរស្តសក្បើ finally។
ស ចរតី ស្ខបរួម្៖
ក្មាប់ការសក្បើក្បា ់ Error handling, សយើ្អាចសក្បើ try…catch, try…finally, ឬ
try…catch…finally។
សៅរនុ្ Error objects មាន properties ដូចជា៖
• name - ក្មាប់បងាហ្ញសឈា្្េះរប ់ error
• message - ក្មាប់បងាហ្ញេ័ត៌មាន ំអិតអំេី error
• stack - ក្មាប់បងាហ្ញេ័ត៌មានអំេី ំដ្ប់ដន nested calls ស្ដ ប្កជា error
២. Introduction to callbacks
Functions ជាសក្ចើនស្ដ ្ត ់សដ្យភាស្ JavaScript អនុញ្ញ្តឱ្យសយើ្រំណត់ រម្មភាេ
asynchronously, មានន័យថា រម្មភាេស្ដ សយើ្ក្បកា ឥ ូវសនេះនឹ្ក្តូវបញ្េប់សេ សក្កាយ។
Function setTimeout គឺជាឧទហរណ៍ម្ួយរនុ្ចំសណ្ម្ functions ទំ្្សនាេះ។
ឧទហរណ៍៖
// script.js
function loadScript(src) {
let script = document.createElement('script'); // *
script.src = src; // **
document.body.append(script); // ***
}
// script.js
loadScript("index.js");
console.log("This console won't wait until loadScript finish.");
// index.js
console.log("index.js will execute after console.log in script.js");
loadScript("anotherScript.js", () => {
});
});
// anotherScript.js
console.log("At this time I'm from anotherScript.js");
loadScript("anotherScript.js", () => {
loadScript("oneAnotherScript.js", () => {
});
});
});
});
});
});
ឧទហរហ៍ខា្ស ើ៖
1. សយើ្ load index.js ក្ប ិនសបើគា្ន error
2. សយើ្ load anotherScript.js ក្ប ិនសបើគា្ន error
3. សយើ្ load oneAnotherScript.js ក្ប ិនសបើគា្ន error សយើ្ដំសណើរការរូដសៅរនុ្
oneAnotherScript.js
៣. Promise
សតើអែីសៅគឺជា Promise ? Promise (in real world) គឺជាការ ន្ាស្ដ នឹ្សរើតស ើ្
សៅសេ ណ្ម្ួយស្ដ បានរំណត់។ ឧទហរណ៍៖ សយើ្ ន្ានឹ្បអូនថាសៅសេ ស្ដ គាត់សរៀន
បានស ខម្ួយ សយើ្នឹ្មានកាដូរជូនគាត់ ដូចសនេះក្ប ិនគាត់ទ្ទ្ួ បានស ខ១េិតស្ម្នគាត់នឹ្
បានទ្ទ្ួ អែីស្ដ សយើ្បាន ន្ា សបើម្ិនដូសចាន្េះសទ្គាត់នឹ្ម្ិនទ្ទ្ួ បានអែីសទ្។ ក្មាប់ Promise
សៅរនុ្ភាស្ JavaScript រ៏ម្ិនខុ គាន្សទ្, Promise គឺជា special object ស្ដ ភាជ្ប់ client side
និ្ server side ជាម្ួយគាន្៖
1. សៅសេ ស្ដ សយើ្ រស ររូដសដើម្្បីដំសណើរការអែីម្ួយ ស្ដ ក្តូវការសេ សវលាសដើម្្បី សក្ម្ច
បាន។ ឧ.ទ្៖ ការទញទ្ិនន
ន ័យេី server ម្រសក្បើសៅស ើ client
2. សៅសេ ស្ដ ទ្ិននន័យម្រដ ់សយើ្អាចយរវាម្រសក្បើដូចជា៖ ការបងាហ្ញេ័ត៌មានរប ់អនរ
សក្បើក្បា ់ ឬការគណនាររចំនួនអនរសក្បើក្បា ់ រុប ។ ។
Syntax រប ់ Promise៖
let promise = new Promise(function(resolve, reject) {
// executor (do something)
});
Promise object ក្តូវបាន return សដ្យ new Promise constructor ស្ដ constructor
សនេះមាន internal properties ដូចជា៖
• state - ការក្បកា ដំបូ្ស្ដ សធែើការរ្់ចាំ (pending), បនាទ្ប់ម្រវាផ្ល្ ប
់ តូរសៅជា
(fulfilled) សៅសេ ស្ដ resolve ក្តូវបាន call សៅ ឬរ៏ (rejected)
សៅសេ ស្ដ reject ក្តូវបាន call សៅ
call សៅ
ដូចសនេះចុ្សក្កាយ executor បតូរ Promise សៅជាម្ួយរនុ្ចំសណ្ម្ state ទំ្
្ េីរសនេះ៖
ឧទហរណ៍ទ្ី១៖
new Promise(function(resolve, reject) {
// the function is executed automatically when the promise is constructed
// after 1 second signal that the job is done with the result "done"
setTimeout(() => resolve("done"), 1000);
});
សៅសេ ស្ដ new Promise ដំសណើរការសយើ្ស ើញថា៖
• executor នឹ្ក្តូវបានសៅសដ្យ យ
ែ័ ក្បវតតិសដ្យ (new Promise)
• executor ទ្ទ្ួ បាន arguments េីរ៖ resolve និ្ reject ។ Functions ទំ្្សនេះ
គឺបានរំណត់សដ្យ JavaScript engine, ដូចសនេះសយើ្ម្ិនចាំបាច់បស្កើតវាសទ្,
អែីស្ដ សយើ្ក្តូវសធែើគឺសៅេួរវាម្រសក្បើ។
បនាទ្ប់េីម្ួយវិនាទ្ីសក្កាយេីដំសណើរការសនេះ, executor បាន call សៅ resolve(“done”) សដើម្្បី
បស្កើតជា ទ្ធ្ ស្ដ ជាដំណ្រ់កា ផ្ល្ ់បតូរ state រប ់ Promise។
ឧទហរណ៍ទ្ី២៖
new Promise(function(resolve, reject) {
▪ catch
ក្ប ិនសបើសយើ្ច្់សក្បើស្ត error, ដូចសនេះសយើ្អាចសក្បើ .catch(err)។
promise.catch((err) => {
console.log(err);
});
promise.then(
(result) => console.log(result)
).catch((err) => {
console.log(err);
});
▪ finally
finally handler អត់មាន arguments សទ្។ សៅរន្
ុ finally េួរសយើ្ម្ិនដឹ្ថា Promise
សជាគជ័យឬរ៏អត់សទ្។ បុស្នតវាម្ិនអីសទ្េីសក្ េះ finally perform ការងារទ្ូសៅ, ស្ដ វាសបាេះ
result ឬ error សៅកាន់ handler បនាទ្ប់។
ឧទហរណ៍ finally និ្ then៖
new Promise((resolve, reject) => {
setTimeout(() => resolve("result"), 2000)
})
.finally(() => console.log("Promise ready")) // Promise ready
.then(result => console.log(result)); // result
Promises Callbacks
Promises អាចឱ្យសយើ្សធែកា
ើ រាម្ ំដ្ប់ ំសដ្យ។ សយើ្ក្តូវមាន callback function ទ្ុរជាម្ុនសៅ
ម្ុនដំប្
ូ សយើ្ដំសណើរការ loadScript(script) សេ ស្ដ សយើ្ call សៅ loadScript(script,
បនាទ្ប់ ម្រ .then
callback)។
ស្ដ សយើ្ រស រនូវអែីស្ដ សយើ្ច្់សធែើ
សៅសេ ស្ដ ទ្ទ្ួ បាន ទ្ធ្ ។ ស ើ េីសនេះសយើ្
អាចសក្បើ .then សក្ចើនដ្ាម្ស្តសយើ្ច្់បាន។
លំហាត់
delayedUpperCase("promise")
.then((result) => console.log(result)) // PROMISE
.catch((err) => console.log(err))
៤. Promise Chaining
ឥ ូវសយើ្រំ ឹរអំេីបញ្ហ្ស្ដ បានស ើរស ើ្សៅរនុ្ចំនុច Introduction to Callbacks
បនតិច, សយើ្បានដឹ្រួចសហើយអំេីដំសណើរការរប ់វាគឺ asynchronously ( ម្ួយចប់បានដំសណើរការ
ម្ួយសទ្ៀត ឬសយើ្និយយបានថាបនតបនាទ្ប់គាន្ ) ឧ.ទ្ loading scripts សដ្យសក្បើក្បា ់ callbacks។
សតើសយើ្មានវិធីស្្ស្សទ្សដើម្្បីសដ្េះក្ស្យរិចេការសនេះឱ្យកាន់ស្តក្បស ើរ? ចសម្លើយ គឺមាន, Promises
្ត ់ឱ្យសយើ្នូវេីររសបៀបសដើម្្បីសដ្េះក្ស្យរិចេការសនេះ។ សៅរនុ្ចំនុចសនេះសយើ្នឹ្និយយអំេី
Promise chaining។
ឧទហរណ៍៖
new Promise(function(resolve, reject) {
}).then(function(result) { // (**)
console.log(result); // 1
return result * 2;
}).then(function(result) { // (***)
console.log(result); // 2
return result * 2;
}).then(function(result) {
console.log(result); // 4
return result * 2;
});
promise.then(function(result) {
console.log(result); // 1
return result * 2;
});
promise.then(function(result) {
console.log(result); // 1
return result * 2;
});
promise.then(function(result) {
console.log(result); // 1
return result * 2;
});
ឧទហរណ៍ខា្ស ើសយើ្សក្បើក្បា ់ 3 handlers សៅកាន់ promise ស្តម្ួយ។ េួរវាម្ិនបាន
សបាេះតដម្លឱ្យគាន្សៅវិញសៅម្រសទ្ គឺេួរវាដំសណើរការដ្ច់សដ្យស្ រេីគាន្។ ដូចសនេះបានជាសយើ្
ទ្ទ្ួ បាន ទ្ធ្ (តដម្ល 1 ទំ្្អ ់)។
}).then(function(result) {
console.log(result); // 1
}).then(function(result) { // (**)
console.log(result); // 2
}).then(function(result) {
console.log(result); // 4
});
ឧទហរណ៍ខា្ស ើ .then ទ្ីម្ួយបងាហ្ញ ទ្ធ្ 1 និ្ returns new Promise(…) ក្ត្់ជួរ
(*)។ បនាទ្ប់េីម្ួយវិនាទ្ីរនល្សៅវា resolve(result * 2) សហើយក្តូវបានសបាេះបនតសៅកាន់ handler
ដន .then ទ្ី២ ស្ដ handler សនេះ ែិតសៅក្ត្់ជួរ (**), បនាទ្ប់ម្រវាបងាហ្ញ ទ្ធ្ 2
និ្ដំសណើរការដូច handler សៅរនុ្ .then ទ្ី១ ដូចគាន្។ ដូចសនេះ ទ្ធ្ ស្ដ ក្តូវបានបងាហ្ញសចញ
ម្រគឺ 1 > 2 > 4, បុស្នតរា ់ការបងាហ្ញ ទ្ធ្ នីម្ួយៗគឺសយើ្បានេន្ារសេ វាម្ួយវិនាទ្ី។
ស ចរតី ស្ខបរួម្៖
ក្ប ិនសបើ .then(handler) return promise, chain (handlers) ស្ដ សៅបនាទ្ប់ក្តូវរ្់ចាំ
ដ ់វាដំសណើរការចប់រួចរា ់សហើយ ិន។ សៅសេ ស្ដ វាដំសណើរការចប់រួចរា ់សហើយ, ទ្ធ្
រប ់វាសទេះជា error ឬ value ក្តូវបានសបាេះបនតសៅកាន់ handler បនាទ្ប់។
})
.then(function(text) {
console.log(text);
})
.catch((err) => console.log(err.message));
ឧទហរណ៍ទ្ី១៖
new Promise((resolve, reject) => {
throw new Error("Pretend as an Error!");
ឧទហរណ៍ទ្ី២៖
new Promise((resolve, reject) => {
reject(new Error("Pretend as an Error!"));
}).then((result) => {
throw new Error("Oh, I'm not okey!"); // rejects the promise
}).then((result) => {
sum(10, 20); // there's no function sum
៥.២ Rethrowing
ដូចស្ដ សយើ្បានដឹ្សហើយ .catch សៅចុ្បញ្េប់ដន chain គឺក្ សដៀ្សៅនឹ្ try … catch
ស្ដរ។ សយើ្អាចមាន .then សក្ចើនាម្ស្តសយើ្ច្់បាន និ្ .catch ម្ួយចុ្សក្កាយ ក្មាប់ក្គប់ក្គ្
error ទំ្្អ ់ស្ដ សរើតមានសៅរនុ្ executor និ្ handlers។
សៅរនុ្ try … catch សយើ្អាចវិភាគសៅស ើ error និ្ក្បស្ហ ជាអាច rethrow វា
ក្ប ិនសបើវាម្ិនអាចក្គប់ក្គ្បាន។ សៅរនុ្ promise សយើ្រ៏អាចសធែើអ៊ីចឹ្បានដូចគាន្។ ក្ប ិនសបើ
សយើ្ throw new Error, បនាទ្ប់ម្រ control នឹ្សលាតសៅកាន់ error handler
ស្ដ សៅជិតបំ្ុត។ ក្ប ិនសបើសយើ្ក្គប់ក្គ្ error និ្បញ្េប់វាសដ្យធម្មា បនាទ្ប់ម្រវានឹ្បនតសៅ
កាន់ .then handler ស្ដ សៅបនាទ្ប់។
ឧទហរណ៍៖
// the execution: catch -> then
new Promise((resolve, reject) => {
}).catch(function(error) {
}).catch(function(error) { // (*)
} else {
console.log("Can't handle such error");
}).then(function() {
/* doesn't run here */
});
The execution សលាតេី .catch ទ្ី១ (*) សៅកាន់ .catch ម្ួយសទ្ៀត (**)
ស្ដ សៅចុ្បញ្េប់ ដន chain។
}).then((result) => {
// successful promise handlers
console.log(result);
});
window.addEventListener('unhandledrejection', function(event) {
// the event object has two special properties:
console.log(event.promise); // Promise {}
console.log(event.reason); // Error: Whoops! there's no catch handler.
});
new Promise(function() {
throw new Error("Whoops! there's no catch handler.");
}); // no catch to handle the error
Event ខា្ស ើគឺជាស្្នរដន HTML។ ក្ប ិនសបើមាន error សរើតស ើ្ សហើយម្ិនមាន .catch,
សនាេះ unhandlerejection handler នឹ្ដំសណើរការ (triggers) បនាទប
្ ់ម្រសយើ្នឹ្ទ្ទ្ួ បាន
event object ម្ួយស្ដ មានេ័ត៌មានអំេី error ដូចសនេះសយើ្អាចសធែើការងារសៅស ើ event
សនាេះបាន។ ម្្ា្្វិញសទ្ៀតសយើ្ក្តូវដឹ្ថាសក្ៅេី browser environments ដូចជា Node.js គឺគា្ន
ម្សធ្ាបាយនឹ្ាម្ដ្ន error ស្បបសនេះបានសទ្។
ស ចរតី ស្ខបរួម្៖
• .catch ក្គប់ក្គ្ errors ក្គប់ក្បសភទ្ទំ្អ ់សៅរនុ្ promises
• សយើ្គួរស្តដ្រ់ .catch សៅរស្នល្ជារ់លារ់ម្ួយស្ដ សយើ្ច្់ក្គប់ក្គ្ errors និ្គួរ
ដឹ្េីរសបៀបក្គប់ក្គ្វា។
• សយើ្ក្តូវស្តសក្បើ .catch ជាដ្ច់ខាត, ក្ប ិនសបើសយើ្ដឹ្ថាគា្្ន្លូវស្្ស្ណ្អាចក្គប់
ក្គ្ error
• រនុ្ររណីខលេះសយើ្គួរស្តមាន unhandledrejection event handler (សៅស ើ
browswer environments) សដើម្្បីាម្ដ្ន unhandled errors និ្ជូនជាដំណឹ្
សៅកាន់អនរសក្បើក្បា ់អំេី error សនាេះ, ដូចសនេះរម្មវិធីសយើ្នឹ្ម្ិនក្តូវបានបញ្េប់ (die)
សទ្
លំហាត់
សតើរូដខា្សក្កាម្ចាប់ error បានសទ្? សបើបានសហតុអែី សបើម្ិនបានសហតុអែី?
new Promise(function(resolve, reject) {
setTimeout(() => {
throw new Error("Whoops!");
}, 1000);
}).catch(console.log);
៦. Promise API
សៅរនុ្ Promise class មានទំ្្អ ់ក្បាំម្ួយ static methods៖ Promise.all,
Promise.allSettled, Promise.race, Promise.any, Promise.resolve, និ្ Promise.reject។
៦.១ Promise.all
នមត់ថាសយើ្ច្់ឱ្យ promises សក្ចើនដំសណើរការរនុ្សេ ស្តម្ួយ និ្ចាំរហូតដ ់ សក្ម្ច
ទំ្្អ ់។ ឧទហរណ៍៖ download បី ឬបួន URLs រនុ្សេ ស្តម្ួយនិ្ដំសណើរការ content ស្តម្ត្
សៅសេ ស្ដ េួរវា សក្ម្ចទំ្្អ ់។ សដើម្្បីសធែើដូចសនេះបានគឺសយើ្ក្តូវសក្បើក្បា ់ Promise.all។
Syntax៖
let promise = Promise.all([...promises...]);
ក្ប ិនសបើមាន promise ណ្ម្ួយក្តូវ reject, promises ស្ដ return សដ្យ Promise.all
នឹ្ reject ភាល្ម្ៗ។
ឧទហរណ៍៖
Promise.all([
new Promise((resolve, reject) => setTimeout(() => resolve(1), 1000)),
new Promise((resolve, reject) => setTimeout(() => reject(new Error("Pretent to
be an error!")), 2000)),
new Promise((resolve, reject) => setTimeout(() => resolve(3), 3000))
]).catch(console.log); // Error: Pretent to be an error!
៦.២ Promise.allSettled
Promise.allSettled ក្គាន់ស្តចាំ្ promises ទំ្
្ អ ់ដំសណើរការរួចរា ់ទំ្្អ ់ និ្ return
ទ្ធ្ អាក្ ័យស ើខលួនវានីម្ួយៗ។ ទ្ធ្ រប ់វាមានទ្ក្ម្្់ដូចខា្សក្កាម្៖
• {status:"fulfilled", value:result} for successful responses,
• {status:"rejected", reason:error} for errors.
៦.៣ Promise.race
ក្ សដៀ្សៅនឹ្ Promise.all, Promise.race ក្គាន់ស្តចាំ promise ណ្ម្ួយស្ដ ដំសណើរការ
សហើយម្ុនសគ និ្យរតដម្លរប ់ promise សនាេះជា ទ្ធ្ រប ់វាសទេះបីជា (resolve/reject)
រ៏សដ្យ។
Syntax៖
let promise = Promise.race(iterable);
ឧទហរណ៍៖
Promise.race([
new Promise((resolve, reject) => setTimeout(() => resolve(1), 1000)),
new Promise((resolve, reject) => setTimeout(() => reject(new Error("Pretend to
be an error!")), 500)),
new Promise((resolve, reject) => setTimeout(() => resolve(3), 3000))
])
.then(console.log)
.catch(console.log) // Error: Pretend to be an error!
៦.៤ Promise.any
ក្ សដៀ្សៅនឹ្ Promise.race, Promise.any យរស្ត promise ណ្ស្ដ fulfill បុសណ្្្េះ,
ក្ប ិនសបើ promises ទំ្្អ ់ reject សនាេះ ទ្ធ្ រប ់វាគឺ promises ស្ដ ក្តូវបាន reject
ទំ្្អ ់សនាេះសដ្យភាជ្បជា
់ ម្ួយនឹ្ special error object (AggregateError) ស្ដ ្ទុរនូវ
promise errors ទំ្្អ ់សៅរនុ្ errors property រប ់វា។
ឧទហរណ៍ទ្ី១៖
Promise.any([
new Promise((resolve, reject) => setTimeout(() => reject(new Error("Error!")),
500)),
new Promise((resolve, reject) => setTimeout(() => resolve(1), 1000)),
new Promise((resolve, reject) => setTimeout(() => resolve(3), 3000))
])
.then(console.log) // 1
.catch(console.log)
ឧទហរណ៍ទ្ី២៖
Promise.any([
new Promise((resolve, reject) => setTimeout(() => reject(new Error("Error1!")),
500)),
new Promise((resolve, reject) => setTimeout(() => reject(new Error("Error2!")),
1000)),
new Promise((resolve, reject) => setTimeout(() => reject(new Error("Error3!")),
1500))
])
.then(console.log)
.catch((err) => {
console.log(err.constructor.name); // AggregateError
console.log(err.errors[0]); // Error: Error1!
console.log(err.errors[1]); // Error: Error2!
console.log(err.errors[2]); // Error: Error3!
})
៦.៥ Promise.resolve/reject
Methods Promise.resolve និ្ Promise.reject គឺរក្ម្សក្បើខលំំា្ណ្ ់ េីសក្ េះសគនិយម្សក្បើ
async/await ស្ដ សយើ្នឹ្ស ើរម្រនិយយសៅចំនុចបនាទ្ប់។ បុស្នតសដើម្្បីជាការបញ្ច្គប់សម្សរៀនសយើ្
ក្តូវស្តដឹ្ទំ្្អ ់គាន្។
▪ Promise.resolve
Promise.resolve(value) បស្កើត promise resolved ម្ួយសដ្យភាជ្ប់ជាម្ួយ ទ្ធ្
value ។ ដូចគាន្សៅនឹ្ let promise = new Promise(resolve => resolve(value));
Promise.resolve('success')
.then((value) => console.log(value));
▪ Promise.reject
Promise.reject('error')
.catch((err) => console.log(err));
ស ចរតី ស្ខបរួម្៖
សៅរនុ្ Promise class មាន static methods ក្បាំម្ួយ៖
1. Promise.all(promises) - វាសធែើការរ្់ចាំរហូតដ ់ promises ទំ្្អ ់ resolve
បនាទ្ប់ម្របាន return ទ្ធ្ សនាេះជា array។ ក្ប ិនសបើមាន promise ណ្ម្ួយ
ក្តូវបាន reject សនាេះ ទ្ធ្ រប ់វាគឺជា Promise ស្ដ ក្តូវបាន reject ម្ុនសគ
ប្អ ់។
៧. Microtasks
Promise handlers .then / .catch / .finally គឺសធែើការ asynchronously (បនតបនាទ្ប់គាន្)។
សទេះបីជា Promise resolved ភាល្ម្ៗរ៏សដ្យ រ៏រូដខា្សក្កាម្េួរវា (.then / .catch / .finally)
នឹ្ក្តូវបានដំសណើរការម្ុន។
ឧទហរណ៍៖
let promise = Promise.resolve();
promise.then(() => console.log("promise done!"));
សដើម្្បីឱ្យកាន់ស្តងាយយ ជា
់ ្សនេះសយើ្គិតស្បបសនេះវិញគឺ សៅសេ ស្ដ promise សក្តៀម្រួច
រា ់សហើយ .then / .cach / .finally handlers រប ់វានឹ្ក្តូវបានដ្រ់បញ្េូ សៅរនុ្ queue
បុស្នតេួរវាម្ិនទន់ដំសណើរការសៅស ើយសទ្។ សៅសេ ស្ដ JavaScript engine ម្ិនមានអែីក្តូវ
execute សទ្ៀតសទ្, វានឹ្សៅយររិចេការ ( handlers ) សនាេះេីរនុ្ queue ម្រវិញ និ្ដំសណើរការ
handlers ទំ្្សនេះាម្ ំដ្ប់ ( FIFO )។ ទំ្្សនេះគឺជាសហតុ្ ស្ដ សៅេីសក្កាយ
console.log("code finished"); ដំសណើរការម្ុនរនុ្ឧទហរណ៍ខា្ស ើ។
ឧទហរណ៍៖
Promise.resolve()
.then(() => console.log("promise done!")) // first
.then(() => console.log("code finished")); // secode
ស ចរតី ស្ខបរួម្៖
Promise handling គឺស្ត្ស្តដំសណើរការបនតបនាទ្ប់គាន្ asynchronously, ដូចសៅនឹ្ promises
ទំ្្អ ់ក្តូវបានបញ្េូ សៅរនុ្ microtasks queue។ ដូចសនេះ .then / .catch / .finally handlers
គឺស្ត្ស្តក្តូវបានដំសណើរការបនាទ្ប់េី current code ( ំសៅសៅស ើ script ទំ្្ម្ូ )
ដំសណើរការចប់។
៨. Async / await
សៅរនុ្ភាស្ JavaScript មាន special syntax ម្ួយស្ដ ដំសណើរការាម្រសបៀប promises
ស្ដ មានភាេងាយក្ ួ យ ់ និ្ងាយក្ ួ រនុ្ការសក្បើក្បា ់គឺក្តូវបានសៅថា async/await។
func().then(console.log); // 1
ដូចសៅនឹ្៖
async function func() {
return Promise.resolve(1);
}
func().then(console.log); // 1
៨.២ Await
Syntax៖
// await ដំសណើរការសៅបានស្តសៅរនុ្ function
// ស្ដ មាន async សៅេីម្ុខស្តបុសណ្្េះ្
let value = await promise;
រ្យថា await គឺមានន័យថាឱ្យ JavaScript ចាំរហូតទ្ ់ស្ត promise settle
(ដំសណើរការចប់) និ្ return ទ្ធ្ រប ់វា។
ឧទហរណ៍៖
async function func() {
let result = await promise; // wait until the promise resolves (*)
func();
Function execution ផ្អ្រ (pauses) ក្ត្់ជួរ (*) និ្បនតស ើ្វិញសៅសេ ស្ដ promise
settle សដ្យភាជ្ប់ជាម្ួយនឹ្ result ស្ដ វានឹ្កាល្យជា ទ្ធ្ ។ ដូចសនេះរូដខា្ស ើបងាហ្ញ "I'm
done!" បនាទ្ប់េីម្ួយវិនាទ្ី។
func();
ឧទហរណ៍សក្បើសៅរនុ្ IIFE៖
( async () => {
let response = await fetch('./user.json');
let user = await response.json();
try {
let response = await fetch('http://abc.eu');
} catch(err) {
console.log(err); // TypeError: failed to fetch
}
}
func();
លំហាត់
ចូរ រស ររូដខា្សក្កាម្ស ើ្វិញជាទ្ក្ម្្់ async/await។
function loadJson(url) {
return fetch(url)
.then((response) => {
if (response.status == 200) {
return response.json();
} else {
throw new Error(response.status);
}
});
}
loadJson('./users/user.json')
.catch(console.log); // Error: 404
មម្មរៀនទី៩ Modules
// sum.js
export function sum (a, b) {
return a + b;
}
សយើ្រ៏មាន file ម្ួយសទ្ៀតស្ដ import file ខា្ស ើម្រសក្បើ៖
// main.js
import { sum } from "./sum.js" //*
The import directives ្ទុរនូវ module សដ្យសក្បើក្បា ់ path (./sum.js) ស្ដ ច្អុ
សៅកាន់ sum.js និ្ assign exported function ម្រកាន់អញ្ញតតិ sum ក្ត្់ជួរ //* ។ សដើម្្បីឱ្យ
module ទំ្្េីរស្គ្ គា
់ បា
ន្ នគឺសយើ្ក្តូវសក្បើ attribute type="module" សៅរនុ្ script ស្ដ សយើ្
សក្បើក្បា ់ ក្មាប់ import ដូចខា្សក្កាម្។
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>repl.it</title>
<link href="style.css" rel="stylesheet" type="text/css" />
</head>
<body>
<script type="module" src="main.js"></script>
</body>
</html>
➢ Module-level scope
// displayMaxNumber.js
console.log(MAX_NUMBER); // ReferenceError: MAX_NUMBER is not defined
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>repl.it</title>
<link href="style.css" rel="stylesheet" type="text/css" />
</head>
<body>
<script type="module" src="displayMaxNumber.js"></script>
<script type="module" src="maxNumber.js"></script>
</body>
</html>
ឧទហរណ៍៖
// console.js
console.log("Module evaluated!");
// a.js
import "./console.js"; // Module evaluated!
// b.js
import "./console.js"; // Nothing shows
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>repl.it</title>
<link href="style.css" rel="stylesheet" type="text/css" />
</head>
<body>
<script type="module" src="a.js"></script>
<script type="module" src="b.js"></script>
</body>
</html>
ឥ ូវសយើ្េិនិត្យសម្ើ ឧទហរណ៍ខា្សក្កាម្៖
// user.js
export const user = {
name: "Dara",
age: 20
};
// a.js
import { user } from "./user.js";
user.age = 30;
console.log(user); // { name: 'Dara', age: 30 }
// b.js
import { user } from "./user.js";
<script type="module">
console.log(this); // undefined
</script>
ឧទហរណ៍៖
<script type="module">
console.log(typeof button); // *
</script>
<script>
console.log(typeof button); // **
</script>
<button id="button">Button</button>
ស ចរតី ស្ខបរួម្៖
1. Modules គឺជា files។ សដើម្្បីដំសណើរការ import/export បាន browsers ក្តូវការ script
type="module"។ Modules មានភាេខុ េី regular scripts៖
o Derred by default
o ម្ិនមាន “bare” modules ណ្ក្តូវបានអនុញ្ញ្តឱ្យសក្បើក្បា ់សទ្
o External script ស្ដ មាន src ដូចគាន្ដំសណើរការស្តម្ត្បុសណ្្្េះ
2. Modules គួរមាន local top-level scope ស្ដ ជារប ់ខលួនវាផ្ទ្ ់សដើម្្បីសធែើការផ្ល្ ់បតូរ
ម្ុខងារគាន្ាម្រយៈ import/export
3. Modules ស្ត្ស្តសក្បើ strict mode (use strict) by default
// export a constant
export const YEAR = 2015;
// export a class
export class User {
constructor(name) {
this.name = name;
}
}
function multiple(a, b) {
return a * b;
}
២.៣ Import *
ក្ប ិនសបើសៅរនុ្ a list of exported មានសក្ចើនសយើ្អាចសក្បើ import * as <obj> សដើម្្បី
import ម្រទំ្្អ ់។
ឧទហរណ៍៖
import * as op from "./operation.js";
op.sum(2, -8);
op.divide(4, 2);
plus(2, -7);
div(3, 3);
function multiple(a, b) {
return a * b;
}
// main.js
import Animal from "./animal.js"; // *
this.name = name;
}
}
៣. Dynamic imports
Export និ្ import statements ស្ដ សយើ្បាន ិរ្ាសៅរនុ្ចំនុចម្ុនក្តូវបានសគសៅថា
“static”។ Static import គឺស្ម្ញ្ញនិ្មានច្ាប់តឹ្រឹ្៖
• ទ្ីម្ួយសយើ្ម្ិនអាចសក្បើ parameters ជាម្ួយ import។ Module path ក្តូវស្តជា string,
ម្ិនអាចជា function call។
import { something } from getModuleName(); // Error,
ឧទហរណ៍ទ្ី១៖
// operation.js
export function sum(a, b) {
return a + b;
}
// main.js
let { sum, multiple } = await import("./operation.js");
console.log(sum(2, 2)); // 4
console.log(multiple(4, 4)); // 16
ឧទហរណ៍ទ្ី២៖
/animal.js
export default class {
constructor(name) {
this.name = name;
}
}
// main.js
let Animal = await import("./animal.js");
ស្ូម្អ្រ្ុែ!
Shortcut Key