Last active
October 9, 2020 03:37
-
-
Save psenger/a8a805e0dd6ddbd2c4e0d50ec678cba1 to your computer and use it in GitHub Desktop.
[Design Pattern: JavaScript Dynamic Proxy] #JavaScript
This file contains hidden or 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
| /** | |
| * 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