Proxy and Reflect: The Spies Behind the Code 🕵️‍♂️💖

JavaScript Guide

In JavaScript, Proxy and Reflect work just like an agent and their trusted partner: one watches everything, the other makes sure things run smoothly. Get ready, — unleash your inner code hacker! 😏💻


1️⃣ Proxy: The Watching Spy 👀

A Proxy is a spy that hides behind an object and watches every move it makes. When a property is accessed, modified, or deleted, Proxy immediately says:
“I’m here. I saw that!” 😎

Example 1: Basic spying 🕵️‍♀️

const target = { name: "Cansu", age: 25 };

const spy = new Proxy(target, {
  get(target, prop) {
    console.log(`Property '${prop}' was accessed!`);
    return target[prop];
  },
  set(target, prop, value) {
    console.log(`Property '${prop}' is being changed to: ${value}`);
    target[prop] = value;
    return true;
  }
});

console.log(spy.name); // 👀 Console: Property 'name' was accessed!
spy.age = 26;          // 📝 Console: Property 'age' is being changed to: 26

Explanation:

  • get: Runs whenever a property is accessed. Logs a message and returns the real value.
  • set: Runs when a property is changed. Logs the change and updates the value.
  • With Proxy, you can now observe object behavior — like James Bond of code! 😎

💡 Tip: get and set aren’t limited to properties; they also work with functions and array elements.


2️⃣ Reflect: The Spy’s Trusted Partner 🛠️

Reflect is the tool that helps Proxy do its job properly. Proxy catches the action, Reflect says:
“Don’t worry, I’ll handle it correctly.” 😏

Example 2: Proxy + Reflect = Perfect spying 🕵️‍♂️💥

const target = { name: "Cansu", age: 25 };

const spy = new Proxy(target, {
  set(target, prop, value) {
    console.log(`Property '${prop}' is being changed to: ${value}`);
    return Reflect.set(target, prop, value);
  },
  get(target, prop) {
    console.log(`Property '${prop}' was requested`);
    return Reflect.get(target, prop);
  }
});

spy.name = "Cansu";
console.log(spy.name);

Explanation:

  • Reflect.set: Safely assigns the value to the target object.
  • Reflect.get: Retrieves the value cleanly and correctly.
  • Reflect keeps Proxy’s spying clean, safe, and drama-free 😏

💡 Practical tip: If you don’t want Proxy to break things, always use Reflect. The spy reports — but doesn’t cause chaos 🕶️


3️⃣ Data Validation with Proxy: “No Negative Age!” 🚫

Proxy doesn’t just watch — it enforces rules.

Example 3: Data validation

const person = { age: 25 };

const superSpy = new Proxy(person, {
  set(target, prop, value) {
    if (prop === "age" && value < 0) {
      console.log("Negative age? No thank you!");
      return false;
    }
    return Reflect.set(target, prop, value);
  }
});

superSpy.age = -5; // Console: Negative age? No thank you!
superSpy.age = 30;
console.log(person.age); // 30

Explanation:

  • Proxy intercepts bad data and blocks it.
  • Reflect safely applies valid changes.
  • Data validation becomes observation + control — true spy style 😎

💡 Tip: Perfect for form validation, user input checks, or limiting game character stats.


4️⃣ Function Spying: Proxy Watches Functions Too! 🎯

Example 4: Tracking function calls

function greet(name) {
  return `Hello ${name}!`;
}

const spyFunction = new Proxy(greet, {
  apply(target, thisArg, args) {
    console.log(`Function '${target.name}' was called! Arguments: ${args}`);
    return Reflect.apply(target, thisArg, args);
  }
});

console.log(spyFunction("Cansu"));

Explanation:

  • apply: Triggers when a function is called.
  • Reflect.apply: Executes the original function and returns the result.
  • Now functions are under surveillance too — who called what, with which arguments 🕵️‍♀️

💡 Practical tip: Amazing for logging, debugging, and performance tracking.


5️⃣ The Ultimate Spy Team: Proxy + Reflect + Custom Rules 💥🕶️

Let’s go wild 😏
An object that watches properties, blocks bad values, and enforces rules.

const agent = {
  name: "007",
  mission: "Code spying"
};

const superAgent = new Proxy(agent, {
  get(target, prop) {
    console.log(`[GET] '${prop}' was requested`);
    return Reflect.get(target, prop);
  },
  set(target, prop, value) {
    if (typeof value === "string" && value.length > 20) {
      console.log("Name too long? Oh no!");
      return false;
    }
    return Reflect.set(target, prop, value);
  }
});

superAgent.name = "James Bond, Code Spy";
console.log(superAgent.mission);

Explanation:

  • Our agent is now unstoppable.
  • Watches properties, enforces rules, keeps everything clean.
  • Code is no longer just functional — it’s fun, safe, and educational 😏💻

💌 Mini Tips:

  • Proxy + Reflect = safe and powerful spying
  • Perfect for validation and logging
  • Works with functions, arrays, and objects
  • Change behavior without touching the original object
  • Widely used behind the scenes in frameworks
    (Vue, Angular, React state management) 😎

Bir yanıt yazın

E-posta adresiniz yayınlanmayacak. Gerekli alanlar * ile işaretlenmişlerdir