Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> JavaScript

การเข้าถึงตัวแปรในฟังก์ชันจากฟังก์ชันอื่น - JavaScript

สาธิตวิธีเข้าถึงตัวแปรที่ประกาศในฟังก์ชันหนึ่ง จากอีกฟังก์ชันหนึ่ง หรือจาก global scope โดยใช้ constructor function และ this

ตัวอย่างโค้ด

const num = 5;

const addRandomToNumber = function(num) {
  const random = Math.floor(Math.random() * 10);
  this.random = random;  // ผูกกับ instance
  this.res = num + random;
};

const addRandomInstance = new addRandomToNumber(num);
const scopedRandom = addRandomInstance.random;
const result = addRandomInstance.res;

console.log(result - scopedRandom); // ต้องเท่ากับ num เดิม (5)

การทำงาน

  • ใช้ new สร้าง instance ของ constructor function
  • this.random และ this.res เก็บค่าไว้ใน instance
  • เข้าถึงได้จากภายนอกผ่าน instance property

วิธีอื่นๆ

  • Closure: return inner function ที่ capture ตัวแปร
  • Module pattern: IIFE return object ที่มี method เข้าถึง private variable
  • Class: ใช้ class กำหนด properties และ methods

ผลลัพธ์

5