JavaScript ရှိ variable မှတစ်ဆင့် Context
ဖြေရှင်းချက်မှာ အောက်ပါအတိုင်းဖြစ်သည်- အပြင်ဘက် function ထဲတွင်
this ကို မည်သည့် variable ထဲမဆို ရေးမှတ်ပြီး ထို variable သည်
အတွင်းဘက် function ထဲသို့ ရောက်ရှိနိုင်မည်ဖြစ်သည်။
variable အားလုံးကဲ့သို့ပင် (ယေဘုယျအားဖြင့် ထို variable ကို
self ဟု ခေါ်ကြသည်)။ ဤနည်းအားဖြင့် ကျွန်ုပ်တို့သည်
this ကို အပြင်ဘက် function မှ အတွင်းဘက် function သို့ လွှဲပြောင်းပေးမည်-
"use strict";
let elem = document.querySelector('#elem');
elem.addEventListener('blur', parent);
function parent() {
console.log(this.value); // 'text' ကို ပြသမည်
let self = this; // this ကို မည်သည့် variable ထဲမဆို ရေးမှတ်ပါ၊ ဥပမာ- self
function child() {
console.log(self.value); // 'text' ကို ပြသမည်
}
child();
}
အောက်ပါ code ကို ပေးထားသည်ဆိုပါစို့-
<input id="elem" value="3">
"use strict";
let elem = document.querySelector('#elem');
elem.addEventListener('blur', func);
function func() {
alert( square() );
function square() {
return this.value * this.value;
}
}
Code ရေးသူသည် focus ပျောက်သွားသောအခါ
input ၏ value မှ ဂဏန်း၏စတုရန်းကို စခရင်ပေါ်တွင်
ပြသစေလိုသည်။ သို့သော်၊ focus ပျောက်သွားသောအခါ
မည်သည့်အကြောင်းကြောင့်မှန်း မသိရသေးသော error ကို console တွင်
�ုတ်ပြသည်။ Code ရေးသူ၏ error ကို ပြင်ဆင်ပေးပါ။
Code ရေးသူအား ၎င်း၏ error မည်ကဲ့သို့ ပေါ်ပေါက်လာသည်ကို
�ှင်းလင်းချက်ပေးသော စာသားကို ရေးပါ။