เราต้องเขียนฟังก์ชัน ที่ทำงานง่ายๆ เช่น บวกเลขสองตัวหรืออะไรประมาณนั้น เราต้องสาธิตวิธีที่เราสามารถเข้าถึงตัวแปรที่ประกาศไว้ภายในฟังก์ชันนั้นในฟังก์ชันอื่นหรือทั่วโลก
ตัวอย่าง
ต่อไปนี้เป็นรหัส -
const num = 5;
const addRandomToNumber = function(num){
// a random number between [0, 10)
const random = Math.floor(Math.random() * 10);
// assigning the random to this object of function
// so that we can access it outside
this.random = random;
this.res = num + random;
};
const addRandomInstance = new addRandomToNumber(num);
const scopedRandom = addRandomInstance.random;
const result = addRandomInstance.res;
// must be equal to the original value of num i.e., 5
console.log(result - scopedRandom); ผลลัพธ์
ต่อไปนี้เป็นผลลัพธ์ในคอนโซล -
5