Created
January 9, 2024 10:36
-
-
Save rubinchyk/bdba9df53b614a17df86e0376c64d507 to your computer and use it in GitHub Desktop.
[Proxy object in javascript] Proxy object in javascript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Data validation and input sanitization. | |
// Logging and debugging to track object interactions. | |
// Implementing access control and security checks. | |
// Creating virtual objects or interfaces. | |
// Implementing lazy loading for properties or data. | |
// Implementing change detection and reactivity (e.g., for UI frameworks). | |
// Caching expensive operations or results. | |
// Implementing object persistence and serialization. | |
// Implementing version control for objects or data. | |
// Intercepting method calls and customizing behavior. | |
// Creating an object to be wrapped by a proxy | |
const targetObject = { | |
name: "John", | |
age: 30 | |
}; | |
// Creating a proxy for the targetObject | |
const proxy = new Proxy(targetObject, { | |
// Handlers for various operations | |
get(target, property) { | |
console.log(`Reading property "${property}"`); | |
return target[property]; | |
}, | |
set(target, property, value) { | |
console.log(`Setting property "${property}" to value "${value}"`); | |
target[property] = value; | |
}, | |
deleteProperty(target, property) { | |
console.log(`Deleting property "${property}"`); | |
delete target[property]; | |
} | |
}); | |
// Using the proxy | |
console.log(proxy.name); // Reading property "name", outputs "John" | |
proxy.age = 35; // Setting property "age" to value "35" | |
console.log(proxy.age); // Reading property "age", outputs "35" | |
delete proxy.name; // Deleting property "name" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment