Bab 3: Object-Oriented Programming dalam JavaScript
Bab 3: Object-Oriented Programming dalam JavaScript
3.1 Konsep Dasar OOP
3.1.1 Pengenalan OOP
Definisi Object-Oriented Programming
Keuntungan menggunakan OOP
Perbedaan OOP dengan functional programming
Use cases untuk OOP dalam JavaScript
3.1.2 Empat Pilar OOP
/*1. Encapsulation: Membungkus data dan method yang memanipulasi data dalam satu unit2. Inheritance: Mewarisi properties dan methods dari class lain3. Polymorphism: Kemampuan object untuk mengambil berbagai bentuk4. Abstraction: Menyembunyikan kompleksitas dan hanya menunjukkan fungsionalitas yang diperlukan*/
class DataStorage {
save(data) {
throw new Error("Method 'save' must be implemented");
}
load() {
throw new Error("Method 'load' must be implemented");
}
}
class FileStorage extends DataStorage {
save(data) {
console.log("Saving to file:", data);
}
load() {
return "Data from file";
}
}
class DatabaseStorage extends DataStorage {
save(data) {
console.log("Saving to database:", data);
}
load() {
return "Data from database";
}
}
3.6 Prototype dan Prototype Chain
3.6.1 Understanding Prototypes
function Student(name) {
this.name = name;
}
Student.prototype.study = function() {
console.log(`${this.name} is studying`);
};
const student1 = new Student("Alice");
console.log(student1.__proto__ === Student.prototype); // true
console.log(Student.prototype.__proto__ === Object.prototype); // true
3.6.2 Prototype Methods dan Properties
// Adding methods to built-in objects (not recommended in production)
Array.prototype.sum = function() {
return this.reduce((a, b) => a + b, 0);
};
const numbers = [1, 2, 3, 4];
console.log(numbers.sum()); // 10
3.7 Design Patterns
3.7.1 Singleton Pattern
class Singleton {
static #instance;
constructor() {
if (Singleton.#instance) {
return Singleton.#instance;
}
Singleton.#instance = this;
}
static getInstance() {
if (!Singleton.#instance) {
Singleton.#instance = new Singleton();
}
return Singleton.#instance;
}
}
3.7.2 Factory Pattern
class Vehicle {
constructor(type, model) {
this.type = type;
this.model = model;
}
}
class VehicleFactory {
createVehicle(type, model) {
switch(type) {
case 'car':
return new Car(model);
case 'truck':
return new Truck(model);
default:
throw new Error('Unknown vehicle type');
}
}
}