JavaScript Class เป็น "Syntactic Sugar" ของ Prototype-based OOP ทำให้เขียนโค้ดคลาสได้เหมือนภาษา OOP ทั่วไป ใช้ใน React, Next.js มาก
Class vs Function
Class และ Function เหมือนกันพื้นฐาน แตกต่างแค่ keyword:
const PlayerFunction = function() {}
const PlayerClass = class {}
// ทั้งคู่ prototype เหมือนกัน: function ()
สร้าง Class
class Book {
constructor(title, author) {
this.title = title;
this.author = author;
}
}
// สร้าง Object (Instance)
const streetcar = new Book("A Streetcar Named Desire", "Tennessee Williams");
console.log(streetcar.title); // "A Streetcar Named Desire"
เพิ่ม Method ใน Class
class Book {
constructor(title, author) {
this.title = title;
this.author = author;
}
getDetails() {
console.log(`${this.title} is a book written by ${this.author}.`);
}
}
streetcar.getDetails(); // "A Streetcar Named Desire is a book written by Tennessee Williams."
Inheritance (การสืบทอด)
class Fiction extends Book {
constructor(title, author, fiction) {
super(title, author); // เรียก constructor คลาสแม่
this.fiction = true;
}
}
const gatsby = new Fiction("The Great Gatsby", "F. Scott Fitzgerald");
console.log(gatsby.fiction); // true
extends- สืบทอดจากคลาสแม่super()- เรียก constructor คลาสแม่
Getters และ Setters
class Book {
constructor(title, author) {
this.title = title;
this.author = author;
}
get author() {
return this.author;
}
set author(author) {
this.author = author;
}
}
const streetcar = new Book("A Streetcar Named Desire", "");
streetcar.author = "Tennessee Williams"; // setter
console.log(streetcar.author); // getter → "Tennessee Williams"
สรุป
Class ทำให้ JavaScript เขียน OOP ได้สะดวก แม้ตัวจริงยังเป็น Prototype ใช้ constructor, extends, super, get/set จัดการข้อมูลได้ดี