Learn
← Previous Next →

Hari 16: Proxy & Reflect

55 min Last updated 09 Apr 2026

Proxy — Interceptor Operasi Object

const handler = {
    get(target, prop) {
        console.log(`Mengakses properti: ${prop}`);
        return prop in target ? target[prop] : `Properti "${prop}" tidak ada`;
    },
    set(target, prop, value) {
        if (typeof value !== "number") throw new TypeError(`${prop} harus number`);
        target[prop] = value;
        return true;
    }
};

const skor = new Proxy({}, handler);
skor.math = 90;   // OK
skor.ipa  = 85;   // OK
// skor.nama = "Budi"; // TypeError!

console.log(skor.math);   // 90
console.log(skor.seni);   // Properti "seni" tidak ada

Reflect

const obj = { a: 1, b: 2, c: 3 };

Reflect.has(obj, "a");             // true (seperti "a" in obj)
Reflect.get(obj, "b");             // 2
Reflect.set(obj, "d", 4);         // true, obj.d = 4
Reflect.deleteProperty(obj, "c"); // true
Reflect.ownKeys(obj);             // ["a", "b", "d"]

💡 Notice: Proxy handler.set() dipanggil setiap kali properti di-set. Sangat powerful untuk validasi, reactive programming, dsb.

Assignment

Buat Proxy untuk validasi form. Setiap kali property di-set, validasi: nama minimal 3 karakter, umur 1-120, email harus mengandung "@". Throw Error jika tidak valid.

Expected output:

Valid: Budi, 25, budi@example.com
Error: Email tidak valid
JS script.js
Solution
Output