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

Best Way สำหรับ Optional Function Parameters ใน JavaScript

วิธีที่ดีที่สุดในปัจจุบัน (ES6+): ใช้ Default Parameters โดยตรงในหัวฟังก์ชัน

ไวยากรณ์

function myFunc(a, b = 0) {
  // function body
}

ตัวอย่าง

<html>
  <body>
    <script>
      function inc(val1, inc = 1) {
        return val1 + inc;
      }

      document.write(inc(10, 10)); // 20
      document.write("<br>");
      document.write(inc(10));     // 11 (ใช้ค่าเริ่มต้น)
    </script>
  </body>
</html>

ข้อดีของ Default Parameters

  • อ่านง่าย ชัดเจน อยู่ที่ Signature
  • <รองรับ Expression: b = computeDefault()
  • รองรับ Destructuring: function foo({x = 1, y = 2} = {})
  • ทำงานกับ arguments object ได้ถูกต้อง (Strict Mode)
  • ไม่ต้องเช็ค undefined เอง

เปรียบเทียบวิธีเก่า

วิธีโค้ดข้อเสีย
Default Parameters (ES6)function(a, b = 1)-
Logical ORb = b || 10, "", false, null จะถูกแทนด้วย 1 (Bug)
Ternaryb = (b !== undefined) ? b : 1Verbose, ต้องเขียนซ้ำ
arguments.lengthif (arguments.length < 2) b = 1;ไม่ทำงานใน Arrow Functions, Strict Mode

Advanced Patterns

// Required Parameter (บังคับส่ง)
const required = () => { throw new Error("Missing parameter"); };
function foo(must = required(), optional = "default") { ... }

// Options Object (หลาย Optional Params)
function fetchData({ url, method = "GET", headers = {}, timeout = 5000 } = {}) { ... }

// Destructuring with Defaults
function connect({ host = "localhost", port = 3000 } = {}) { ... }

สรุป: ใช้ Default Parameters เป็นหลัก ร่วมกับ Options Object สำหรับฟังก์ชันที่มี Optional Parameters มาก