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

การสืบทอด (Inheritance) ใน JavaScript แบบ Prototype

JavaScript เป็นภาษาที่พัฒนาจาก Prototype-based Programming การสืบทอด (Inheritance) ทำงานผ่าน Prototype Chain โดยออบเจ็กต์จะสืบทอดคุณสมบัติและเมธอดจาก Prototype ของมัน

ตัวอย่าง: สืบทอดด้วย Prototype

<!DOCTYPE html>
<html lang="th">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>JavaScript Inheritance</title>
    <style>
        body { font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif; }
        .result { font-size: 18px; font-weight: 500; color: blueviolet; }
        button { padding: 8px 16px; margin: 10px 0; cursor: pointer; }
    </style>
</head>
<body>
    <h1>การสืบทอด (Inheritance) ใน JavaScript</h1>
    <div class="result"></div>
    <button class="Btn">เรียกเมธอด welcome() ที่สืบทอดมา</button>
    <h3>กดปุ่มเพื่อเรียกเมธอด welcome() ที่ person1 และ person2 สืบทอดมา</h3>

    <script>
        let BtnEle = document.querySelector(".Btn");
        let resEle = document.querySelector(".result");
        
        // Constructor Function (คลาสแบบเก่า)
        function Person(name, age, city) {
            this.name = name;
            this.age = age;
            this.city = city;
        }
        
        // เพิ่มเมธอดใน Prototype (แบ่งปันให้ทุก Instance)
        Person.prototype.welcome = function() {
            resEle.innerHTML += `👋 สวัสดี ${this.name} อายุ: ${this.age} เมือง: ${this.city}<br>`;
        };
        
        BtnEle.addEventListener("click", () => {
            let person1 = new Person("Rohan", 22, "Delhi");
            person1.welcome();
            
            let person2 = new Person("Shawn", 19, "England");
            person2.welcome();
        });
    </script>
</body>
</html>

ผลลัพธ์

กดปุ่ม: แสดง
👋 สวัสดี Rohan อายุ: 22 เมือง: Delhi
👋 สวัสดี Shawn อายุ: 19 เมือง: England

โครงสร้าง Prototype Chain

person1 → Person.prototype → Object.prototype → null
   │              │
   │              └─ welcome() (แบ่งปัน)
   │
   └─ name, age, city (เฉพาะตัว)

ES6 Classes (ไวยากรณ์ใหม่ ที่แปลงเป็น Prototype เช่นเดิม)

class Person {
    constructor(name, age, city) {
        this.name = name;
        this.age = age;
        this.city = city;
    }
    
    welcome() {
        console.log(`สวัสดี ${this.name} อายุ ${this.age} เมือง ${this.city}`);
    }
}

class Student extends Person {
    constructor(name, age, city, studentId) {
        super(name, age, city); // เรียก Constructor ของ Parent
        this.studentId = studentId;
    }
    
    study() {
        console.log(`${this.name} กำลังอ่านหนังสือ...`);
    }
}

const student = new Student("Somchai", 20, "Bangkok", "STU001");
student.welcome(); // สืบทอดมาจาก Person
student.study();   // เมธอดของตัวเอง

Object.create() - สืบทอดโดยตรงจากออบเจ็กต์

const animal = {
    breathe() { console.log("หายใจ..."); }
};

const dog = Object.create(animal);
dog.bark = () => console.log("Woof!");

dog.breathe(); // สืบทอดจาก animal
dog.bark();    // เมธอดของตัวเอง

สรุปประเภทการสืบทอด

รูปแบบคำอธิบาย
Prototype Delegationใช้ Constructor.prototype.method = ...
ES6 Class extendsSyntactic Sugar ของ Prototype (แนะนำ)
Object.create()สร้างออบเจ็กต์ใหม่โดยระบุ Prototype โดยตรง
Mixin / Compositionผสมฟังก์ชันจากหลายแหล่ง (ไม่ใช่ Inheritance จริง)