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

วิธีหา Caller Function (ฟังก์ชันที่เรียก) ใน JavaScript

ใช้ property function.caller เพื่อดูว่าฟังก์ชันไหนเป็นตัวเรียกฟังก์ชันปัจจุบัน หมายเหตุ: เป็น non-standard feature และ obsolete ใน strict mode

ตัวอย่างการใช้งาน

<html>
  <head>
    <script type="text/javascript">
      function Display() {
        alert("caller is " + Display.caller);
      }
    </script>
  </head>
  <body>
    <p>คลิกปุ่มด้านล่าง:</p>
    <form>
      <input type="button" onclick="Display()" value="Get caller function">
    </form>
  </body>
</html>

การทำงาน

  • เมื่อคลิกปุ่ม → เรียก Display()
  • Display.caller จะคืนค่าฟังก์ชันที่เรียก (ในที่นี้คือ event handler)
  • ถ้าเรียกจาก global scope จะได้ null

ข้อจำกัดและคำเตือน

1. ไม่ทำงานใน Strict Mode

'use strict';
function test() {
  console.log(test.caller); // TypeError: 'caller' not allowed in strict mode
}

2. Non-standard / Deprecated

  • ไม่ได้อยู่ใน ECMAScript specification
  • อาจถูกลบในอนาคต
  • เบราว์เซอร์บางตัวอาจไม่รองรับ

3. arguments.caller (Obsolete)

function oldWay() {
  console.log(arguments.caller); // Obsolete - อย่าใช้
}

ทางเลือกที่ดีกว่า (Best Practices)

1. ส่ง Context ผ่าน Parameter

function callee(context) {
  console.log('Called by:', context);
}

function caller() {
  callee('caller'); // ส่งชื่อหรือ reference เอง
}

2. ใช้ Error Stack Trace

function getCaller() {
  const stack = new Error().stack;
  const lines = stack.split('\n');
  // lines[2] มักจะเป็น caller (ขึ้นอยู่กับเบราว์เซอร์)
  return lines[2]?.trim();
}

3. ใช้ Console.trace() สำหรับ Debug

function debugMe() {
  console.trace('Trace from debugMe');
}

สรุป

อย่าใช้ function.caller ในโปรดักชัน - ใช้ parameter passing, error stack, หรือ console.trace แทน