javascript

Proxy


A proxy in JavaScript is an object that serves as an intermediary between the code and the target object it wraps. Proxies enable us to intercept and customize fundamental operations performed on objects, such as property lookup, assignment, invocation, and more. They provide a flexible mechanism for implementing custom behavior transparently without modifying the target object directly.

 

Creating Proxy:

Creating a proxy using the Proxy constructor, which takes two parameters: the target object and a handler object. The target object is the object that the proxy wraps, and the handler object contains traps, which are methods that intercept fundamental operations on the target object.
 

// creating proxy
const target = {};
const handler = {
	get: function(target, property, receiver) {
    	console.log(`Getting property: ${property}`);
    	return Reflect.get(target, property, receiver);
	},
	set: function(target, property, value, receiver) {
    	console.log(`Setting property: ${property} = ${value}`);
    	return Reflect.set(target, property, value, receiver);
	}
};
const proxy = new Proxy(target, handler);

 

Traps:

It is method defined in the handler object that intercept fundamental operations on the target object. These operations include property access, property assignment, function invocation, and more. Each trap corresponds to a specific operation, allowing you to customize behavior as needed.
 

const handler = {
    get: function(target, property, receiver) {
      // Custom behavior for property access
    },
    set: function(target, property, value, receiver) {
      // Custom behavior for property assignment
    },
    // Other traps...
};