Skip to content

Instantly share code, notes, and snippets.

@psenger
Last active October 9, 2020 03:37
Show Gist options
  • Select an option

  • Save psenger/a8a805e0dd6ddbd2c4e0d50ec678cba1 to your computer and use it in GitHub Desktop.

Select an option

Save psenger/a8a805e0dd6ddbd2c4e0d50ec678cba1 to your computer and use it in GitHub Desktop.
[Design Pattern: JavaScript Dynamic Proxy] #JavaScript
/**
* Dynamic Proxy
*
* Wrapping an object with a proxy, and references the previous values.
* Services is an Object with mixed values, of which is a function ( or even functions ).
*/
const Services = {
firstname: 'Anita',
surname: 'Bath',
gender: 'female',
salutation: function() {
return `${Services.firstname} ${Services.surname}`
}
}
console.log(Services.salutation());
// Anita Bath
const ProxyServices = {
...Services // shallow copy
}
console.log('ProxyServices=', JSON.stringify(ProxyServices, null, 4));
// ProxyServices= {
// "firstname": "Anita",
// "surname": "Bath",
// "gender": "female"
// }
console.log(ProxyServices.salutation());
// Anita Bath
for (const [key,value] of Object.entries(Services)) {
if ( value instanceof Function ) {
ProxyServices[key] = (...a) => {
return `Greetings ${Services.gender === 'male' ? 'Mr' : 'Mrs'} ${Services[key](...a)}`
}
}
}
console.log('ProxyServices=', JSON.stringify(ProxyServices, null, 4));
// ProxyServices= {
// "firstname": "Anita",
// "surname": "Bath",
// "gender": "female"
// }
console.log(ProxyServices.salutation());
// Greetings Mrs Anita Bath
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment