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

Native Prototypes ใน JavaScript: ขยาย Built-in Objects


JavaScript เป็นภาษา prototype-based ทุกอ็อบเจกต์มี prototype เป็นโครงสร้างพื้นฐานของการสืบทอด (inheritance) Native Prototypes คือ prototypes ของ built-in objects เช่น Object.prototype, Array.prototype, String.prototype, Function.prototype ฯลฯ เราสามารถเพิ่มเมธอด/พร็อพเพอร์ตี้ใหม่เข้าไปได้ (Monkey Patching) แต่ไม่ควรลบ ค่าที่มีอยู่เดิม

ตัวอย่างโค้ด: เพิ่มเมธอด alternateCase ให้ String

<!DOCTYPE html>
<html lang="th">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title>Native Prototypes</title>
  <style>
    body { font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif; }
    .result, .sample { font-size: 18px; font-weight: 500; color: rebeccapurple; }
    .sample { color: red; }
  </style>
</head>
<body>
  <h1>Native Prototypes ใน JavaScript</h1>
  <div class="sample"></div>
  <div class="result"></div>
  <button class="Btn">คลิกที่นี่</button>
  <h3>กดปุ่มเพื่อแปลงสตริงเป็นตัวพิมพ์ใหญ่-เล็กสลับกันด้วย prototype</h3>
  <script>
    const resEle = document.querySelector(".result");
    const sampleEle = document.querySelector(".sample");
    const btnEle = document.querySelector(".Btn");
    // เพิ่มเมธอดใหม่ให้ String.prototype
    String.prototype.alternateCase = function () {
      let newStr = "";
      for (let i = 0; i < this.length; i++) {
        newStr += i % 2 === 0 ? this[i].toUpperCase() : this[i].toLowerCase();
      }
      return newStr;
    };
    const str = "HELLO WORLD";
    sampleEle.textContent = "ต้นฉบับ: " + str;
    btnEle.addEventListener("click", () => {
      resEle.textContent = "ผลลัพธ์: " + str.alternateCase();
    });
  </script>
</body>
</html>

ผลลัพธ์

Native Prototypes ใน JavaScript: ขยาย Built-in Objects

เมื่อกดปุ่ม "คลิกที่นี่":

Native Prototypes ใน JavaScript: ขยาย Built-in Objects

Native Prototypes หลัก

Prototypeใช้กับเมธอดตัวอย่าง
Object.prototypeทุกอ็อบเจกต์toString(), hasOwnProperty()
Array.prototypeอาร์เรย์map(), filter(), reduce(), flat()
String.prototypeสตริงslice(), replace(), trim()
Function.prototypeฟังก์ชันcall(), apply(), bind()
Number.prototypeตัวเลขtoFixed(), toPrecision()
Date.prototypeวันที่toISOString(), getTime()
Promise.prototypePromisethen(), catch(), finally()

⚠️ ข้อควรระวัง (Best Practices)

  • อย่าลบ/เขียนทับเมธอดเดิม — จะทำลายโค้ดไลบรารี/โค้ดอื่นที่พึ่งพาพฤติกรรมมาตรฐาน
  • หลีกเลี่ยง Monkey Patching ในโปรดักชัน — ก่อให้เกิด bug ยากหา conflict กับ library อื่น
  • ใช้ Symbol สำหรับเมธอดภายใน — ป้องกันชนชื่อ: String.prototype[Symbol.myMethod] = ...
  • พิจารณา Utility Functions แทน — const alternateCase = (str) => ... แทนการแก้ prototype
  • Polyfill ถูกต้อง: ตรวจสอบก่อนเพิ่ม if (!String.prototype.alternateCase) { ... }

ตัวอย่าง Polyfill ที่ปลอดภัย

if (!String.prototype.trimStart) {
  String.prototype.trimStart = function() {
    return this.replace(/^\s+/, '');
  };
}

สรุป

Native Prototypes ให้พลังมากแต่ต้องใช้ระมัดระวัง ในโปรเจกต์ใหญ่ แนะนำให้ใช้ Utility Functions หรือ Wrapper Classes แทน การแก้ prototype ควรจำกัดเฉพาะ Polyfill มาตรฐานที่ขาดหายไปเท่านั้น