Proxies in js
Roushan Kumar
Lead Frontend Developer | React.js | JavaScript (ES6+) | MERN Stack | TypeScript | Redux.js | Next.js | Node.js | MongoDB | SaaS Product Development | Team Leadership | Lifelong Learner | Open to Opportunities
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? ??
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
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..?