What is Proxy design pattern?
JavaScript Native Proxy
javascript
const user = {
name: 'John',
age: 30
};
const handler = {
get(target, prop) {
console.log(`Reading ${prop}`);
return target[prop];
},
set(target, prop, value) {
console.log(`Setting ${prop} to ${value}`);
if (prop === 'age' && typeof value !== 'number') {
throw new TypeError('Age must be a number');
}
target[prop] = value;
return true;
}
};
const proxy = new Proxy(user, handler);
console.log(proxy.name); // Reading name → John
proxy.age = 31; // Setting age to 31 ✅
proxy.age = 'thirty'; // TypeError! ❌Caching Proxy
javascript
class ImageProxy {
constructor(image) {
this.image = image;
this.cache = null;
}
display() {
if (!this.cache) {
console.log('Loading image...');
this.cache = this.image.load();
}
return this.cache; // From cache
}
}
// Usage
const image = new RealImage('photo.jpg');
const proxy = new ImageProxy(image);
proxy.display(); // Loads
proxy.display(); // From cache!Access Control Proxy
javascript
const sensitiveData = {
password: 'secret123',
apiKey: 'key123'
};
const protectedData = new Proxy(sensitiveData, {
get(target, prop) {
if (prop === 'password' || prop === 'apiKey') {
throw new Error('Access denied');
}
return target[prop];
}
});
console.log(protectedData.password); // Error! ❌Use Cases
✅ Lazy loading ✅ Caching ✅ Validation ✅ Access control ✅ Logging ✅ Vue/Mobx reactivity
Short Answer
Interview readyPremium
A concise answer to help you respond confidently on this topic during an interview.