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

Function() Constructor ใน JavaScript คืออะไร?

Function() constructor ใช้ใน JavaScript เพื่อสร้าง function object ใหม่ Objects ที่สร้างจะถูก parse เมื่อฟังก์ชันถูกสร้าง

ตัวอย่าง

<html> 
  <body> 
    <script> 
      var num = new Function('p', 'q', 'r', 'return p * q * r'); 
      document.write("Value after multiplication: " + num(5, 2, 9)); 
    </script> 
  </body> 
</html>

Syntax

new Function([arg1[, arg2[, ...argN]],] functionBody)
  • Arguments สุดท้ายคือ function body (string)
  • Arguments ก่อนหน้าเป็น parameter names (strings)
  • สร้างฟังก์ชันใน global scope เท่านั้น (ไม่สร้าง closure)

⚠️ ข้อเสียและข้อควรระวัง

ปัญหาคำอธิบาย
Securityรัน string code — คล้าย eval() ระวัง XSS
PerformanceParse ทุกครั้งที่สร้าง — ช้ากว่า declaration/expression
No closureไม่เข้าถึง outer scope ได้ (เฉพาะ global)
Debuggingยาก — ไม่มีชื่อใน stack trace
CSPอาจถูกบล็อกโดย Content Security Policy

เมื่อไหร่ควรใช้

เกือบไม่มีกรณีที่ควรใช้ — ยกเว้น dynamic code generation ที่จำเป็นมาก (เช่น template engines, REPL) แนะนำใช้ function declaration/expression/arrow แทน