Proxies in js

JavaScript proxies are a game-changer, offering powerful capabilities to intercept and customize operations on objects. Whether you're a seasoned developer or just diving into JS, understanding proxies can significantly enhance your coding toolkit.

What are JS Proxies? ??

Proxies allow you to create objects with custom behavior for fundamental operations (like property lookup, assignment, enumeration, function invocation, etc.). They provide a way to intercept and redefine these operations, making them incredibly versatile.

Why Use Proxies? ??

  1. Interception of Operations: Customize how properties are accessed, assigned, or even deleted.
  2. Validation: Enforce rules dynamically, ensuring data integrity.
  3. Virtualization: Create virtual properties that are computed or fetched only when accessed.
  4. Logging & Debugging: Centralize logging of object interactions, making debugging easier.
  5. Security: Enforce access control and security policies.
  6. API Migrations: Handle deprecated methods gracefully, guiding users towards new APIs.

Real-World Examples ??

Logging Property Access and Assignment:

const handler = { get: (target, prop) => { console.log(`Getting property ${prop}`); return target[prop]; }, set: (target, prop, value) => { console.log(`Setting property ${prop} to ${value}`); target[prop] = value; return true; } }; const proxy = new Proxy({}, handler); proxy.name = 'Alice'; // Logs: Setting property name to Alice console.log(proxy.name); // Logs: Getting property name, Output: Alice

Validation of Property Values:

const handler = {
 set: (target, prop, value) => { 
if (prop === 'age' && typeof value !== 'number') {
 throw new TypeError('Age must be a number'); 
}
 target[prop] = value; return true; 
}
 }; 
const proxy = new Proxy({}, handler); 
proxy.age = 25; // Works fine
 proxy.age = 'twenty-five'; // Throws error: Age must be a number        

Preventing Property Deletion:

const handler = { 
deleteProperty: (target, prop) => { 
if (prop === 'password') { 
console.log('You cannot delete the password property'); return false; } 
delete target[prop]; 
return true;
 } 
};

 const proxy = new Proxy({ password: 'secret' }, handler); 
delete proxy.password; // Logs: You cannot delete the password property console.log(proxy.password); // Output: secret        

#fallinlovewithjavaScript


Vinay Kumar

Fullstack Developer | React.js | Next.js | JavaScript |TypeScript | Redux | Node | Express| Mongodb | Docker |AWS.

9 个月

Abey... Bihari kuch to acha likh leta . Shakal acchi nahin diya Bhagwan Ne To kam se kam kaam to acche kar le..?

回复

要查看或添加评论,请登录

社区洞察

其他会员也浏览了