A Proxy in JavaScript

_Khojiakbar_ - Jul 19 - - Dev Community

A Proxy in JavaScript is a special object that allows you to customize the behavior of fundamental operations (e.g., property lookup, assignment, enumeration, function invocation, etc.) on another object. It's like having a mischievous middleman who can intercept and alter interactions with an object.

Why Do We Need Proxies?

Proxies are useful for various reasons:

  1. Validation: Ensure data integrity by validating assignments.
    Logging: Track operations on an object for debugging or monitoring.

  2. Default Values: Provide default values when properties are accessed.

  3. Access Control: Restrict or modify access to certain properties.

  4. Virtual Properties: Define properties that don't physically exist on the object.

Funny Examples to Understand Proxies

Example 1: The Overprotective Parent

Imagine you have a kid named Timmy, and you want to make sure he doesn’t eat too many cookies. You act as an overprotective parent, monitoring and controlling his cookie intake.

let timmy = {
  cookies: 3
};

let overprotectiveParent = new Proxy(timmy, {
  get(target, property) {
    console.log(`Overprotective Parent: "Timmy currently has ${target[property]} ${property}."`);
    return target[property];
  },
  set(target, property, value) {
    if (property === 'cookies' && value > 5) {
      console.log('Overprotective Parent: "No, Timmy, you can’t have more than 5 cookies!"');
      return false;
    }
    console.log(`Overprotective Parent: "Alright, Timmy, you can have ${value} ${property}."`);
    target[property] = value;
    return true;
  }
});

// Checking Timmy's cookies
console.log(overprotectiveParent.cookies); // Overprotective Parent: "Timmy currently has 3 cookies."

// Trying to give Timmy too many cookies
overprotectiveParent.cookies = 6; // Overprotective Parent: "No, Timmy, you can’t have more than 5 cookies!"

// Setting a reasonable number of cookies
overprotectiveParent.cookies = 4; // Overprotective Parent: "Alright, Timmy, you can have 4 cookies."
console.log(overprotectiveParent.cookies); // Overprotective Parent: "Timmy currently has 4 cookies."
Enter fullscreen mode Exit fullscreen mode
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Terabox Video Player