[Part 6] JS: OOP & Inheritance

[Part 6] JS: OOP & Inheritance

Photo by Dan Gold / Unsplash

OOP Fundamental

Object-Oriented Programming (OOP) ภาษาไทย: การเขียนโปรแกรมเชิงวัตถุ เป็นรูปแบบการเขียนโปรแกรมชนิดหนึ่ง ที่นักพัฒนาให้การยอมรับ และเป็นที่นิยม (ในอดีต) สำหรับโปรแกรมที่เริ่มมีความซับซ้อน โดยมีลักษณะเบื้องต้น

  1. การมองโปรแกรมเสมือนวัตถุหนึ่งอย่าง เช่น นก รถยนต์
  2. การมองค่า หรือตัวแปรของโปรแกรม เป็นคุณสมบัติ เช่น นกมีน้ำหนัก 2 kg, รถยนต์ มีความเร็ว 60 km/hr
  3. การมองฟังก์ชันการทำงานของโปรแกรม เป็น พฤติกรรม เช่น นกบินได้, รถยนต์สามารถวิ่งไปข้างหน้าได้

OOP Backbone

  1. Encapsulation การห่อหุ้มข้อมูล
  2. Abstraction การรู้แค่ที่จำเป็น
  3. Inheritance การสืบทอดคุณสมบัติ
  4. Polymorphism การมีหลายรูปแบบ

OOP Vocabulary

  1. Method คือ Function ของโปรแกรมนั้นๆ เปรียบเทียบกับพฤติกรรมหรือการทำงานของวัตถุ
  2. Attribute คือ Variable ที่ระบุให้วัตถุนั้นๆ เปรียบได้กับ ตัวแปร หรือ ค่าคงที่ของโปรแกรม
  3. Class คือ การสร้างชนิดของข้อมูลใหม่ ตามที่เราต้องการ โดยอาศัยหลักการทำงานของ OOP เป็นพื้นฐาน สามารถระบุ method, attribute ได้ตามที่ programmer ต้องการ
  4. Object คือ ข้อมูลที่เกิดขึ้น หลังจากสร้าง class แล้ว เราสามารถสร้าง object ที่มี attribute ที่ต่างกันได้ โดยใช้พื้นฐานจาก class เดียวกัน
  5. Blueprint หรือ Prototype คือสิ่งเดียวกับ class หลังจากสร้าง class แล้ว จะเปรียบเสมือนมีแม่แบบ ในการสร้าง Object ใดๆ ก็ได้ โดยใช้ method, attribute ของ class นั้นๆ

ใน JavaScript, class เป็นโครงสร้างที่ใช้สร้างวัตถุ (object) ที่มีคุณสมบัติ (properties) และพฤติกรรม (methods) คล้ายกับภาษาอื่นๆ เช่น Python หรือ Java แต่ภายใต้ระบบ prototype-based ของ JavaScript

Class Creation

Constructor

เป็นการกำหนด Attribute ให้กับ object ทำให้ object แต่ละตัวมีค่าที่แตกต่างกันได้

class Person {
  constructor(name) {
    this.name = name;
  }
}

const john = new Person("John");
const mary = new Person("Mary")

Method

เป็นการกำหนดการทำงาน (พฤติกรรม) ของ class ที่เราสร้างขึ้นมา ใช้หลักการเดียวกับฟังก์ชัน

class Person {
  constructor(name, age) {
    this.name = name;
    this.age = age;
  }

  introduce() {
    console.log(`Hi, I'm ${this.name}, I'm ${this.age} years old.`);
  }
}

const john = new Person("John", 20);
john.introduce();

Modify attribute

  • แก้ไขผ่าน Attribute (ไม่ควรทำ)
class Person {
  constructor(name, age) {
    this.name = name;
    this.age = age;
  }

  introduce() {
    console.log(`Hi, I'm ${this.name}, I'm ${age} years old.`);
  }
}

const john = new Person("John", 20);
john.age = 20;
  • ควรใช้หลักการ Encupsulation โดยใช้ผ่าน Private Field
class BankAccount {
  #balance;

  constructor(initialBalance) {
    this.#balance = initialBalance;
  }

  deposit(amount) {
    this.#balance += amount;
  }

  getBalance() {
    return this.#balance;
  }
}

const account = new BankAccount(1000);
account.deposit(500);
console.log(account.getBalance());
// console.log(account.#balance); // SyntaxError: Private field '#balance' must be declared

Static Methods และ Attributes

เป็นสมาชิกของคลาสที่ไม่สามารถเข้าถึงผ่าน instance ได้ แต่สามารถเรียกใช้ผ่านคลาสโดยตรง

class MathUtil {
  static PI = 3.14;
  static square(x) {
    return x * x;
  }
}
console.log(MathUtil.PI);
console.log(MathUtil.square(5));

Type checking

สามารถใช้ instanceof เพื่อตรวจสอบว่า object เป็น instance ของคลาสใด

console.log(account instanceof BankAccount); // true
console.log(john instanceof Person);  // true

Inheritance

เป็นการสืบทอด class โดยเราจะมองว่าโปรแกรมเชิงวัตถุ สามารถมีคุณสมบัติคล้ายคลึงกัน แต่เปลี่ยนแปลงบางอย่างได้ โดยจะเรียก class หลักว่า parent และ class ที่สืบทอดว่า child

โดย syntax ที่ต้องระบุเพิ่มได้แก่

  1. class ที่เป็น child ต้องระบุ class parent ตอนประกาศ class
  2. ถ้าต้องการสืบทอด properties และ attribute จาก parent ต้องใช้ super()
class Student extends Person {
  constructor(name, age, studentId) {
    super(name, age);
    this.studentId = studentId;
  }

  getStudentId() {
    return this.studentId
  }
}

const alice = new Student("Alice", 17, "S12345");
alice.introduce();
console.log(alice.getStudentId());

Replace parent methods

class Student extends Person {
  constructor(name, age, studentId) {
    super(name, age);
    this.studentId = studentId;
  }

  introduce() {
    console.log(`Hi, I'm ${this.name}, I'm ${this.age} years old. ID: ${this.studentId}`);
  }

  getStudentId() {
    return this.studentId
  }

}

const alice = new Student("Alice", 17, "S12345");
alice.introduce();
console.log(alice.getStudentId());

Exercise

  1. สร้าง class ของรถยนต์ (car) โดยมี properties และ method ดังนี้
    1. properties: สี, ชนิดของรถ, ความเร็ว (km/hr)
    2. method:
      1. ขับ (drive): ให้แสดงผล driving
      2. method คำนวนเวลาที่ใช้ในการเดินทาง: ให้รับค่า parameter เป็นระยะทาง จากนั้น ให้นำความเร็วมาหาร และแสดงผลเป็นเวลาที่ใช้ในการเดินทาง
    3. โจทย์
      1. ให้แสดงผลสีของรถยนต์ Benz
      2. ให้แสดงผลระยะเวลาที่ใช้ขับรถ BMW ถ้ากำหนดความเร็ว = 200, สี = black, ชนิดของรถ = sedan
  2. สร้าง class ของ Person กำหนดให้มีเพศ, อายุ, ชื่อจริง, นามสกุล จากนั้นให้สร้าง child class ชื่อ Student โดยให้สืบทอดคุณสมบัติของ Person แต่มีค่าที่เพิ่มมา คือ เลขประจำตัวนักเรียน และ ชั้นเรียน
    1. แสดงผล ข้อมูลบัตรประจำตัวนักเรียนเมื่อ Student("male", 15, "Pathompat", "Sungpankhao", "67001202961", "grade 6")
    2. ทดสอบแสดงผลชั้นเรียนของ Person("female", 23, "Malinee", "Kunthong")

Assignment

  1. เปลี่ยนฟังก์ชันและตัวแปรที่เคยใช้ใน assignment เดิมเป็น attribute และ method โดยสร้าง class ชื่อ CourseOnlineUser
    1. กำหนด attribute คือ id, username, password, firstname, lastname, course
    2. กำหนด method
      1. login(username, password)
      2. getEnrollList()
      3. checkEnrollStatus(userId, courseName)
      4. updateEnrollment(userId, courseName, duration)
  2. กำหนดให้ run code นี้แล้วได้ผลลัพธ์ดังนี้
const mungCourses = [
  {
    name: "Programming 101",
    status: "STUDYING",
    totalDuration: 180,
    takenDuration: 65,
    expiredAt: "2025-07-20 00:00:00"
  }
]
const mung = new CourseOnlineUser(1, "mungggy", "Test#1234", "Pathompats", "Sungpankhao", mungCourses);

mung.login("mungggy", "123456");
// Failed: invalid username & password
mung.login("mungggy", "Test#1234");
// Login success

mung.getEnrollList();
// Show mungCourses that status = ENROLLED

mung.checkEnrollStatus("Biology 101");
// Enroll not found 

mung.checkEnrollStatus("Programming 101");
// Enroll found: Programming 101, status: STUDYING, duration: 65/180

mung.updateEnrollment("Programming 101", 30);
// Updated enroll: Programming 101, duration: 95/180

Reference

[Part 5] JS: Function
Function ฟังก์ชัน (Function) คือบล็อกของโค้ดที่ออกแบบมาเพื่อทำงานเฉพาะอย่าง โดยสามารถรับข้อมูลนำเข้า (parameters) และส่งค่ากลับ (return value) ได้ // Function with no parameter and return function hello() { console.log(‘Hello, world!’); } // Function with only return value function greet() { return `hello! user`; } // Function
Object-oriented programming in Python
Object-oriented Programming from the ground up with Pikachu and Bay Area Rapid Transit (BART)
[Part 6] Python 101: Class & OOP & Inheritance
OOP Fundamental Object-Oriented Programming (OOP) ภาษาไทย: การเขียนโปรแกรมเชิงวัตถุ เป็นรูปแบบการเขียนโปรแกรมชนิดหนึ่ง ที่นักพัฒนาให้การยอมรับ และเป็นที่นิยม (ในอดีต) สำหรับโปรแกรมที่เริ่มมีความซับซ้อน โดยมีลักษณะเบื้องต้น 1. การมองโปรแกรมเสมือนวัตถุหนึ่งอย่าง เช่น นก