Masukkan Password
45 Metode & Properti Statis
Lecture ini membahas static properties dan static methods pada class TypeScript.
Kalau lecture sebelumnya kita belajar bahwa property/method biasa dimiliki oleh masing-masing object/instance, sekarang kita belajar sesuatu yang berbeda:
Static property dan static method dimiliki oleh class-nya, bukan oleh setiap instance.
Ini konsep yang cukup penting karena berhubungan dengan pertanyaan:
βApakah data/behavior ini memang milik setiap object, atau sebenarnya milik class secara keseluruhan?β
Mari kita uraikan pelan-pelan.
1. Mulai dari memahami Instance
Misalnya kita punya class:
class Product {
name: string;
price: number;
color: string;
calcDiscount() {
// ...
}
availability() {
// ...
}
}
Kemudian kita membuat:
const product1 = new Product();
const product2 = new Product();
const product3 = new Product();
Kita sekarang memiliki 3 instance.
Secara konsep:
Product
β
βββββββββββΌββββββββββ
β β β
product1 product2 product3
Setiap instance memiliki akses terhadap property dan method instance dari class tersebut.
2. Instance Property
Misalnya:
class Product {
name: string;
price: number;
}
name dan price adalah instance properties.
Artinya, setiap object mempunyai nilainya sendiri.
Contoh:
const product1 = new Product();
product1.name = "Laptop";
product1.price = 1000;
const product2 = new Product();
product2.name = "Phone";
product2.price = 500;
Sekarang:
product1
βββ name = "Laptop"
βββ price = 1000
product2
βββ name = "Phone"
βββ price = 500
Nilai name dan price berbeda untuk masing-masing object.
3. Instance Method
Misalnya:
class Product {
calcDiscount() {
// ...
}
availability() {
// ...
}
}
Ini adalah instance methods.
Kita memanggilnya melalui object:
product1.calcDiscount();
product1.availability();
atau:
product2.calcDiscount();
product2.availability();
Jadi secara penggunaan:
instance
β
product1.calcDiscount()
product2.calcDiscount()
product3.calcDiscount()
4. Lalu apa itu Static?
Sekarang kita menggunakan keyword:
static
Misalnya:
class Product {
name: string;
price: number;
static color: string;
}
Sekarang color bukan lagi instance property.
color adalah:
static property
Artinya property tersebut berada pada class, bukan pada setiap object.
5. Perbedaan paling penting
Ini yang harus benar-benar kamu pahami:
Instance property
class Product {
name: string;
}
Diakses melalui:
product.name
Static property
class Product {
static color: string;
}
Diakses melalui:
Product.color
Perhatikan perbedaannya:
Instance property
β
product.name
Static property
β
Product.color
Yang satu menggunakan instance.
Yang satu menggunakan class.
6. Analogi sederhana
Bayangkan class Employee.
Ada 100 employee.
Setiap employee punya:
nama
gaji
alamat
Ini merupakan informasi yang berbeda-beda untuk setiap employee.
Jadi cocok menjadi instance properties:
employee.name
employee.salary
employee.address
Tetapi ada informasi seperti:
“Berapa jumlah employee yang dibuat?”
Ini bukan milik satu employee tertentu.
Ini milik Employee secara keseluruhan.
Maka cocok dibuat:
Employee.count
Nah, inilah contoh penggunaan static property.
7. Contoh Employee dari lecture
Misalnya:
class Employee {
firstName: string;
lastName: string;
count: number = 0;
constructor(firstName: string, lastName: string) {
this.firstName = firstName;
this.lastName = lastName;
this.count++;
}
}
Kemudian:
const emp1 = new Employee("John", "Smith");
console.log(emp1.count);
Hasilnya:
1
Lalu:
const emp2 = new Employee("Mary", "Jane");
console.log(emp2.count);
Hasilnya:
1
Kenapa bukan 2?
8. Karena count adalah instance property
Perhatikan:
count: number = 0;
Karena count bukan static, setiap kali kita menggunakan:
new Employee()
kita mendapatkan instance baru dengan:
count = 0
Kemudian constructor menjalankan:
this.count++;
Jadi:
Employee 1
emp1
count = 0
β
constructor
β
count++
β
count = 1
Employee 2
emp2
count = 0
β
constructor
β
count++
β
count = 1
Maka:
emp1.count // 1
emp2.count // 1
9. Sekarang ubah menjadi Static
Kita ubah:
count: number = 0;
menjadi:
static count: number = 0;
Sekarang:
class Employee {
firstName: string;
lastName: string;
static count: number = 0;
constructor(firstName: string, lastName: string) {
this.firstName = firstName;
this.lastName = lastName;
Employee.count++;
}
}
Perhatikan ada perubahan penting:
Sebelumnya:
this.count++;
Sekarang:
Employee.count++;
Kenapa?
Karena count sekarang bukan milik instance.
count milik class Employee.
10. Bagaimana cara mengakses static property?
Bukan:
emp1.count
Tetapi:
Employee.count
Contoh:
const emp1 = new Employee("John", "Smith");
console.log(Employee.count);
Output:
1
Kemudian:
const emp2 = new Employee("Mary", "Jane");
console.log(Employee.count);
Output:
2
Kemudian:
const emp3 = new Employee("David", "Brown");
console.log(Employee.count);
Output:
3
11. Kenapa sekarang menjadi 1, 2, 3?
Karena hanya ada satu count yang digunakan bersama.
Bayangkan:
Employee
β
static count = 0
β
βββββββββββΌββββββββββ
β β β
emp1 emp2 emp3
β β β
βββββββββββΌββββββββββ
β
Employee.count
Ketika emp1 dibuat:
count: 0 β 1
Ketika emp2 dibuat:
count: 1 β 2
Ketika emp3 dibuat:
count: 2 β 3
Karena semuanya menggunakan static Employee.count yang sama.
12. Ini perbedaan fundamentalnya
Instance property:
Employee
β
βββ emp1 β count sendiri
βββ emp2 β count sendiri
βββ emp3 β count sendiri
Static property:
Employee
β
βββ count
β
β
ββββββΌβββββ
β β β
emp1 emp2 emp3
Jadi:
Instance property = masing-masing object punya data sendiri.
Static property = satu data yang dimiliki bersama oleh class.
13. Kenapa this.count tidak bisa digunakan?
Ini bagian penting dari lecture.
Ketika kita berada di constructor:
constructor(...) {
this.count++;
}
this menunjuk ke instance yang sedang dibuat.
Misalnya:
const emp1 = new Employee(...);
maka di constructor:
this
mengacu kepada:
emp1
Kalau:
const emp2 = new Employee(...);
maka:
this
mengacu kepada:
emp2
Sedangkan static property tidak berada di emp1 atau emp2.
Static property berada di:
Employee
Maka:
this.count
β salah untuk static property.
Yang benar:
Employee.count
14. this vs nama class
Ini pola yang sangat penting untuk diingat.
Instance member
Gunakan:
this.property
Contoh:
this.firstName
this.lastName
karena property tersebut milik instance.
Static member
Gunakan:
ClassName.property
Contoh:
Employee.count
karena property tersebut milik class.
Jadi:
Instance
β
this.firstName
Class
β
Employee.count
15. Static Method
Sekarang kita masuk ke static method.
Misalnya:
class Employee {
getFullName() {
return "John Smith";
}
}
Ini adalah instance method.
Kita memanggil:
const emp = new Employee();
emp.getFullName();
Karena method tersebut dimiliki oleh instance.
16. Mengubah menjadi Static Method
Kita bisa menulis:
class Employee {
static sayHello() {
return "Hi there";
}
}
Sekarang sayHello() adalah static method.
Cara memanggilnya:
Employee.sayHello();
Bukan:
const emp = new Employee();
emp.sayHello(); // β
Jadi:
Instance method
β
emp.getFullName()
Static method
β
Employee.sayHello()
17. Kenapa static method tidak dipanggil lewat instance?
Karena static method memang tidak menjadi member dari instance.
Bayangkan:
Employee
βββ static count
βββ static sayHello()
β
β
βββ milik class
emp1
βββ firstName
βββ lastName
βββ instance methods
emp1 tidak memiliki:
sayHello()
Jadi:
emp1.sayHello();
β error.
Tetapi:
Employee.sayHello();
β benar.
18. Kenapa this tidak bisa digunakan di static method?
Lecture juga menekankan hal ini.
Misalnya:
class Employee {
firstName: string;
static sayHello() {
console.log(this.firstName);
}
}
Ini bermasalah.
Kenapa?
Karena this di instance method dan static method memiliki konteks berbeda.
Pada instance method:
emp.getFullName()
this mengacu kepada:
emp
Tetapi pada static method:
Employee.sayHello()
this mengacu kepada class/static context, bukan instance employee tertentu.
Dan yang paling penting:
Static method tidak tahu employee mana yang dimaksud.
Misalnya ada:
emp1 = John
emp2 = Mary
emp3 = David
Kalau kita memanggil:
Employee.sayHello()
pertanyaannya:
“John, Mary, atau David?”
Tidak ada instance tertentu.
19. Contoh yang mudah membedakan
Misalnya:
class Employee {
constructor(
public firstName: string,
public lastName: string
) {}
getFullName() {
return `${this.firstName} ${this.lastName}`;
}
static sayHello() {
return "Hi there";
}
}
Kita buat:
const emp1 = new Employee("John", "Smith");
const emp2 = new Employee("Mary", "Jane");
Instance method:
emp1.getFullName();
hasil:
John Smith
Sedangkan:
emp2.getFullName();
hasil:
Mary Jane
Karena this berbeda.
Tetapi:
Employee.sayHello();
hasil:
Hi there
Tidak ada hubungan dengan John atau Mary.
Method tersebut adalah behavior yang berkaitan dengan Employee class secara umum, bukan employee tertentu.
20. Kapan menggunakan Static?
Pertanyaan paling penting:
“Kapan sesuatu sebaiknya static?”
Jawabannya:
Gunakan static ketika sesuatu tidak membutuhkan data dari instance tertentu.
Misalnya:
Employee.count
Kita tidak bertanya:
“Berapa jumlah employee milik John?”
Kita bertanya:
“Berapa jumlah employee yang sudah dibuat?”
Itu informasi global untuk class Employee.
21. Contoh penggunaan Static yang masuk akal
Misalnya kita punya:
class MathHelper {
static add(a: number, b: number) {
return a + b;
}
}
Kita tidak perlu membuat:
const helper = new MathHelper();
hanya untuk menjumlahkan angka.
Kita cukup:
MathHelper.add(10, 20);
hasil:
30
Kenapa static?
Karena add() tidak membutuhkan informasi dari object MathHelper tertentu.
22. Contoh lain: counter
Static sangat cocok untuk counter.
class Employee {
static count = 0;
constructor() {
Employee.count++;
}
}
Kemudian:
new Employee();
new Employee();
new Employee();
console.log(Employee.count);
hasil:
3
Karena count memang mewakili:
jumlah seluruh instance Employee.
23. Static property bukan berarti “dibuat sekali lalu tidak berubah”
Ini juga penting.
Static bukan berarti:
immutable.
Misalnya:
class Employee {
static count = 0;
}
Nilai count masih bisa berubah:
Employee.count++;
Employee.count++;
Employee.count = 100;
static hanya menentukan:
siapa pemilik property tersebut?
Bukan:
apakah nilainya boleh berubah?
Kalau ingin property static tidak boleh diubah, konsepnya berbeda, misalnya menggunakan readonly:
class Config {
static readonly companyName = "ABC";
}
24. Static dan readonly bisa digabung
Contohnya:
class AppConfig {
static readonly version = "1.0.0";
}
Kemudian:
console.log(AppConfig.version);
β boleh.
Tetapi:
AppConfig.version = "2.0.0";
β tidak boleh.
Di sini ada dua konsep:
static
β
milik class
readonly
β
tidak boleh di-reassign
25. Static property bisa memiliki access modifier
Misalnya:
class Employee {
public static count = 0;
private static secret = "abc";
}
public static:
Employee.count;
bisa diakses dari luar.
Sedangkan:
Employee.secret;
β tidak bisa karena private.
Jadi access modifier dan static adalah dua konsep yang berbeda.
public/private/protected
β
mengatur ACCESS
static
β
mengatur PEMILIK / CONTEXT
26. Ini sangat penting: static β singleton
Kadang pemula melihat:
static count
dan mengira:
“Berarti cuma boleh ada satu object.”
Tidak.
Kita tetap bisa membuat:
const emp1 = new Employee();
const emp2 = new Employee();
const emp3 = new Employee();
Ada 3 object.
Yang hanya satu adalah static member-nya:
Employee
β
βββ static count
Jadi:
Jumlah object = bisa banyak
Jumlah static data = satu per class
27. Visualisasi paling penting
Instance property
Employee
β
ββββββββββΌβββββββββ
β β β
emp1 emp2 emp3
β β β
name name name
salary salary salary
Setiap instance memiliki data sendiri.
Static property
Employee
β
β
static count
β
ββββββββββΌβββββββββ
β β β
emp1 emp2 emp3
Hanya ada satu count.
Semua instance berhubungan dengan static member yang sama melalui class.
28. Instance Method vs Static Method
| Instance | Static | |
|---|---|---|
| Milik | Object/instance | Class |
| Dipanggil lewat | object.method() | Class.method() |
| Bisa menggunakan data instance | β | β secara langsung |
Menggunakan this untuk instance | β | Tidak untuk instance |
Perlu new untuk mengakses | Ya | Tidak |
| Contoh | emp.getFullName() | Employee.sayHello() |
29. Instance Property vs Static Property
| Instance | Static | |
|---|---|---|
| Contoh | name | count |
| Milik | Instance | Class |
| Akses | emp.name | Employee.count |
| Setiap object punya salinan sendiri | Ya | Tidak |
| Data bisa berbeda tiap object | Ya | Tidak, satu member bersama |
30. Cara menentukan “static atau tidak?”
Ini trik yang sangat berguna.
Tanyakan:
“Apakah nilai ini berbeda untuk setiap object?”
Kalau ya, kemungkinan besar instance property.
Contoh:
Employee
βββ firstName
βββ lastName
βββ salary
βββ address
John dan Mary punya nilai berbeda.
Jadi:
employee.firstName
employee.salary
Kalau jawabannya:
“Tidak. Nilai ini berlaku untuk seluruh class.”
Maka kemungkinan cocok menjadi static.
Contoh:
Employee
βββ count
count menghitung seluruh employee.
Maka:
Employee.count
31. Contoh dunia nyata
Bayangkan class:
class BankAccount
Setiap account punya:
accountNumber
ownerName
balance
Ini instance properties.
Karena:
Account A β balance 1 juta
Account B β balance 5 juta
Account C β balance 10 juta
Tetapi bank mungkin punya:
totalAccounts
yang menunjukkan berapa banyak account dibuat.
Itu cocok menjadi:
static totalAccounts
32. Contoh lain: Product
Misalnya:
class Product {
name: string;
price: number;
static totalProducts = 0;
constructor(name: string, price: number) {
this.name = name;
this.price = price;
Product.totalProducts++;
}
}
Kemudian:
const p1 = new Product("Laptop", 1000);
const p2 = new Product("Phone", 500);
const p3 = new Product("Mouse", 50);
Kita bisa:
console.log(p1.name);
hasil:
Laptop
Karena name adalah instance property.
Sedangkan:
console.log(Product.totalProducts);
hasil:
3
Karena totalProducts adalah static property.
33. Kesalahan umum pemula
Salah 1
class Employee {
static count = 0;
}
const emp = new Employee();
console.log(emp.count);
β Salah.
Karena count static.
Yang benar:
console.log(Employee.count);
Salah 2
Menggunakan this untuk static property:
class Employee {
static count = 0;
constructor() {
this.count++;
}
}
β Tidak tepat.
Gunakan:
Employee.count++;
Salah 3
Memanggil static method melalui object:
class Employee {
static sayHello() {}
}
const emp = new Employee();
emp.sayHello();
β Salah.
Gunakan:
Employee.sayHello();
34. Hubungan dengan lecture sebelumnya
Kalau kita hubungkan dengan materi sebelumnya:
Instance property
public name: string;
private salary: number;
protected dateOfBirth: string;
readonly employeeId: number;
Semua ini berkaitan dengan instance, kecuali jika ditambahkan static.
Misalnya:
private salary: number;
berarti:
setiap employee punya salary sendiri dan salary tersebut private.
Sedangkan:
private static count: number;
berarti:
class Employee memiliki satu
countstatic yang private.
Jadi static bisa dikombinasikan dengan access modifier.
35. Satu kalimat untuk membedakan semuanya
Coba lihat:
class Employee {
public name: string;
private salary: number;
protected department: string;
static count: number = 0;
}
Artinya:
name
β
setiap Employee punya name
salary
β
setiap Employee punya salary
dan hanya Employee yang boleh mengaksesnya
department
β
setiap Employee punya department
dan class turunan juga boleh mengaksesnya
count
β
bukan milik setiap Employee
melainkan milik class Employee
36. Mental model terakhir
Bayangkan:
CLASS
Employee
β
βββββββββββββ΄ββββββββββββ
β β
STATIC INSTANCE
β β
β β
Employee.count emp1.name
Employee.sayHello() emp1.salary
emp1.getSalary()
Jadi pertanyaan yang harus kamu tanyakan adalah:
“Saya mau mengakses sesuatu dari class atau dari object?”
Kalau dari object:
employee.name
employee.getSalary()
β instance
Kalau dari class:
Employee.count
Employee.sayHello()
β static
π§ Ringkasan super singkat
Instance
class Employee {
name: string;
getFullName() {}
}
Digunakan:
const emp = new Employee();
emp.name;
emp.getFullName();
Artinya:
milik masing-masing object.
Static
class Employee {
static count = 0;
static sayHello() {}
}
Digunakan:
Employee.count;
Employee.sayHello();
Artinya:
milik class secara keseluruhan.
Ingat aturan emas:
INSTANCE
β
object.property
object.method()
STATIC
β
Class.property
Class.method()
Dan untuk this:
this
β
instance yang sedang bekerja
ClassName
β
class/static context
Jadi inti lecture ini bukan sekadar βtambahkan keyword static.β Yang lebih penting adalah memahami ownership:
Kalau data/behavior berkaitan dengan satu object tertentu, gunakan instance member.
Kalau data/behavior berkaitan dengan class secara keseluruhan, gunakan static member.