Created
May 20, 2024 16:58
-
-
Save helabenkhalfallah/c6b2f1da0b9e864993f296abb8631977 to your computer and use it in GitHub Desktop.
Proxy Combined Example
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
const target = { | |
name: 'Alice', | |
age: 30, | |
} | |
const handler = { | |
get: function(target, prop, receiver) { | |
console.log(`Getting property ${prop}`); | |
return Reflect.get(target, prop, receiver); | |
}, | |
set: function(target, prop, value, receiver) { | |
console.log(`Setting property ${prop} to ${value}`); | |
target[prop] = value; | |
return true; | |
}, | |
has: function(target, prop) { | |
console.log(`Checking if property ${prop} is in target.`); | |
return prop in target; | |
}, | |
deleteProperty: function(target, prop) { | |
console.log(`Deleting property ${prop}.`); | |
delete target[prop]; | |
return true; | |
}, | |
apply: function(target, thisArg, argumentsList) { | |
console.log(`Called with arguments: ${argumentsList}`); | |
return target.apply(thisArg, argumentsList); | |
}, | |
ownKeys: function(target) { | |
console.log('Getting property keys.'); | |
return Reflect.ownKeys(target); | |
} | |
}; | |
const proxy = new Proxy(target, handler); | |
// Using get trap | |
console.log(proxy.name); // Logs: Getting property name. Output: Alice | |
// Using set trap | |
proxy.age = 35; // Logs: Setting property age to 35 | |
console.log(target.age); // Output: 35 | |
// Using has trap | |
console.log('name' in proxy); // Logs: Checking if property name is in target. Output: true | |
// Using deleteProperty trap | |
delete proxy.age; // Logs: Deleting property age. | |
console.log(target.age); // Output: undefined | |
// Using ownKeys trap | |
console.log(Object.keys(proxy)); // Logs: Getting property keys. Output: ['name'] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment