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

วิธีประกาศ Optional Parameters ใน JavaScript Function

ใช้ Default Parameters (ES6) เพื่อประกาศ Optional Parameters ได้โดยตรงใน Function Signature

ตัวอย่างจากบทความ

<html>
  <body>
    <script>
      // default is set to 1
      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>

รูปแบบ Optional Parameters

1. ค่าเริ่มต้นแบบ Primitive

function createUser(name, role = 'user', active = true) {
  return { name, role, active };
}

createUser('John');              // {name: 'John', role: 'user', active: true}
createUser('Jane', 'admin');     // {name: 'Jane', role: 'admin', active: true}
createUser('Bob', 'user', false); // {name: 'Bob', role: 'user', active: false}

2. ค่าเริ่มต้นจาก Expression/Function

function generateId() {
  return Math.random().toString(36).substr(2, 9);
}

function createRecord(data, id = generateId(), timestamp = Date.now()) {
  return { ...data, id, timestamp };
}

3. ใช้ Parameter ก่อนหน้าเป็น Default

function createPoint(x = 0, y = x, z = x + y) {
  return { x, y, z };
}

createPoint();       // {x: 0, y: 0, z: 0}
createPoint(5);      // {x: 5, y: 5, z: 10}
createPoint(5, 10);  // {x: 5, y: 10, z: 15}

4. Destructuring กับ Default

function connect({ 
  host = 'localhost', 
  port = 3000, 
  secure = false,
  timeout = 5000
} = {}) { // = {} ทำให้เรียก connect() ได้โดยไม่ส่งอะไร
  console.log(`Connecting to ${host}:${port}`);
}

connect();                          // localhost:3000
connect({ port: 8080 });            // localhost:8080
connect({ host: 'api.com', secure: true }); // api.com:3000

วิธีเก่า (ES5) - ใช้ || หรือ ternary

function oldStyle(name, role) {
  name = name || 'Guest';        // ปัญหา: '' หรือ 0 จะกลายเป็น 'Guest'
  role = role !== undefined ? role : 'user'; // ดีกว่า
  
  // หรือ
  if (arguments.length < 2) role = 'user';
}

Required Parameter Pattern

function required(paramName) {
  throw new Error(`Missing required parameter: ${paramName}`);
}

function createUser(name = required('name'), email = required('email'), age = 18) {
  return { name, email, age };
}

createUser('John', 'john@example.com'); // OK
createUser('John'); // Error: Missing required parameter: email

ข้อควรระวัง

  • Default parameters ทำงาน เฉพาะเมื่อค่าเป็น undefined (ไม่ได้ส่ง หรือ ส่ง undefined ตรงๆ)
  • ส่ง null → ไม่ใช้ default (คือ null)
  • Default expression รันทุกครั้งที่เรียกฟังก์ชัน (ไม่ cache)
  • Parameters ที่มี default ควรอยู่ท้าย (แต่ JS ไม่บังคับ)

สรุป

รูปแบบตัวอย่างหมายเหตุ
Primitive defaultfoo(a = 1)พื้นฐาน
Expression defaultfoo(a = Date.now())รันทุกครั้ง
Previous paramfoo(a, b = a)อ้างอิง param ก่อนหน้า
Destructuringfoo({a = 1} = {})Object params
Requiredfoo(a = required('a'))บังคับให้ส่ง