how to create a proxy variable in javascript

In JavaScript, we can use Proxy objects to define custom behavior for fundamental operations (like property lookup, assignment, enumeration, function invocation, etc.) on an object. We can create a proxy variable by using new Proxy(target, handler) syntax, where target is the object to be proxied, and handler is a set of traps for the fundamental operations.

Here's an example:

index.tsx
let targetVariable = 42;

let handler = {
  get: function(target, name) {
    console.log(`Getting property "${name}"`);
    return target[name];
  },
  set: function(target, name, value) {
    console.log(`Setting property "${name}" to ${value}`);
    target[name] = value;
    return true;
  }
};

let proxyVariable = new Proxy(targetVariable, handler);

console.log(proxyVariable); // 42
proxyVariable = 100;
console.log(proxyVariable); // 100
447 chars
20 lines

In this example, we have created a proxy proxyVariable for the targetVariable using an object handler with two traps get and set. get trap is invoked when a property of proxyVariable is read/accessed and set trap is invoked when a property of proxyVariable is modified. In both traps, we log messages to the console and delegate the operations to the targetVariable.

related categories

gistlibby LogSnag