JavaScript dikenal fleksibel dalam mengelola objek dan kelas. Setelah memahami dasar object literal, property, method, dan class sederhana, saatnya naik ke level advanced patterns yang sering digunakan dalam proyek profesional.
Bab ini membahas Mixins, Factory Functions, Private & Protected Fields, Object Freezing, dan Dynamic Properties.
Contents
1. Mixins
Mixin adalah pola untuk menambahkan fungsi atau properti ke objek atau kelas lain tanpa menggunakan inheritance tradisional. Ini sangat berguna untuk reuse behavior tanpa membuat hierarki class kompleks.
const canEat = {
eat() {
console.log(`${this.name} is eating.`);
}
};
const canWalk = {
walk() {
console.log(`${this.name} is walking.`);
}
};
class Person {
constructor(name) {
this.name = name;
}
}
// Menggabungkan mixin ke Person prototype
Object.assign(Person.prototype, canEat, canWalk);
const john = new Person("John");
john.eat(); // John is eating.
john.walk(); // John is walking.
Manfaat:
- Reuse fungsi lintas class
- Hindari multiple inheritance
- Mempermudah composability behavior
2. Factory Function vs Constructor vs Class
Ada tiga cara membuat objek di JavaScript:
a. Factory Function
Fungsi yang mengembalikan objek baru. Tidak menggunakan new.
function createPerson(name, age) {
return {
name,
age,
greet() {
console.log(`Hi, I'm ${name}`);
}
};
}
const alice = createPerson("Alice", 25);
alice.greet(); // Hi, I'm Alice
b. Constructor Function
Fungsi khusus yang dipanggil dengan new.
function Person(name, age) {
this.name = name;
this.age = age;
}
Person.prototype.greet = function() {
console.log(`Hi, I'm ${this.name}`);
};
const bob = new Person("Bob", 30);
bob.greet(); // Hi, I'm Bob
c. Class (ES6+)
Sintaks modern yang syntactic sugar dari constructor function.
class PersonClass {
constructor(name, age) {
this.name = name;
this.age = age;
}
greet() {
console.log(`Hi, I'm ${this.name}`);
}
}
const charlie = new PersonClass("Charlie", 28);
charlie.greet(); // Hi, I'm Charlie
Perbandingan:
| Feature | Factory | Constructor | Class |
|---|---|---|---|
new keyword | ❌ | ✅ | ✅ |
| Prototype | ❌/manual | ✅ | ✅ |
| Private fields | ❌ | ❌ | ✅ |
3. Private & Protected Fields (Modern JS)
ES2020 memperkenalkan private fields menggunakan #. Ini membuat properti tidak bisa diakses di luar class.
class BankAccount {
#balance = 0; // private field
constructor(owner) {
this.owner = owner;
}
deposit(amount) {
this.#balance += amount;
console.log(`Deposited ${amount}, new balance: ${this.#balance}`);
}
getBalance() {
return this.#balance;
}
}
const account = new BankAccount("Alice");
account.deposit(100); // Deposited 100, new balance: 100
console.log(account.getBalance()); // 100
// console.log(account.#balance); // ❌ SyntaxError
Protected fields tidak native di JS, tapi bisa disimulasikan dengan convention _fieldName.
class Person {
constructor(name) {
this._name = name; // protected (konvensi)
}
}
4. Object Freezing & Sealing
JavaScript menyediakan cara untuk membatasi modifikasi objek.
a. Object.freeze()
Objek tidak bisa diubah: tidak bisa tambah, hapus, atau ubah property.
const obj = { name: "Alice" };
Object.freeze(obj);
obj.name = "Bob"; // ❌ tidak berubah
console.log(obj.name); // Alice
b. Object.seal()
Objek tidak bisa ditambah/hapus property, tapi bisa ubah nilai property yang sudah ada.
const obj2 = { name: "Charlie" };
Object.seal(obj2);
obj2.name = "David"; // ✅ bisa diubah
obj2.age = 30; // ❌ tidak bisa ditambah
console.log(obj2); // { name: "David" }
5. Dynamic Property & Method Creation
Kamu bisa membuat properti atau method secara dinamis di runtime.
const propName = "score";
const obj = {
[propName]: 100, // dynamic property
[`show${propName.charAt(0).toUpperCase() + propName.slice(1)}`]() {
console.log(this[propName]);
}
};
obj.showScore(); // 100
Manfaat:
- Membuat objek fleksibel sesuai kondisi runtime
- Digunakan dalam meta-programming dan framework modern
Kesimpulan
Bab ini membekali kamu dengan pola lanjutan dalam membuat dan mengelola objek serta class:
- Mixins → reuse behavior tanpa inheritance
- Factory / Constructor / Class → fleksibilitas membuat objek
- Private fields → keamanan properti
- Object freezing & sealing → proteksi objek
- Dynamic properties & methods → fleksibilitas runtime
Menguasai pola ini membuat kode lebih modular, aman, dan maintainable, serta menjadi fondasi untuk design pattern tingkat lanjut dan framework modern.