Kịch bản thuyết trình: Slides 144, 145
Mình tiếp tục với slide 144 và 145 về JavaScript Classes.
Ví dụ: Quản lý xe ô tô
1. Class Car (cha):
- Có
constructor(name, year)để khởi tạo thuộc tính. - Có instance method
getAge()để tính tuổi xe. - Có static method
compareAge()để so sánh 2 chiếc xe, gọi trực tiếp quaCar.compareAge().
2. Class Model (con):
- Sử dụng
extends Carđể kế thừa. - Trong constructor, dùng
super(name, year)để gọi constructor của Car. - Thêm method
showInfo()để hiển thị thông tin chi tiết.
3. Tạo object từ class con:
const car1 = new Model("Toyota", 2015, "Corolla");
Tạo một xe có đủ thông tin name, year, model.
4. Gọi method:
car1.showInfo()→ gọi method của class con.car1.getAge()→ kế thừa từ class cha.Car.compareAge(car1, car2)→ gọi static method của class cha.
Code đầy đủ:
// Parent class
class Car {
constructor(name, year) {
this.name = name;
this.year = year;
}
// Instance method
getAge() {
const age = new Date().getFullYear() - this.year;
return `${this.name} is ${age} years old.`;
}
// Static method
static compareAge(car1, car2) {
return car1.year - car2.year;
}
}
// Child class
class Model extends Car {
constructor(name, year, model) {
super(name, year); // call parent constructor
this.model = model;
}
// Instance method
showInfo() {
return `${this.name} ${this.model} (${this.year})`;
}
}
// Create objects
const car1 = new Model("Toyota", 2015, "Corolla");
const car2 = new Model("Honda", 2018, "Civic");
// Use instance methods
console.log(car1.showInfo()); // Toyota Corolla (2015)
console.log(car1.getAge()); // Toyota is X years old
// Use static method
console.log(Car.compareAge(car1, car2)); // -3
Như vậy là mình đã trình bày xong về JavaScript Classes, cách tạo class cha/con, sử dụng constructor, instance method và static method.