Created
February 17, 2020 21:43
-
-
Save iainjreid/8c262c52096e120432c508f46229c67b to your computer and use it in GitHub Desktop.
Default properties using a JavaScript Proxy
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
const dog = defaultProperties({ | |
breed: 'Dachshund', | |
name: 'Sam', | |
age: 3 | |
}, 'empty'); | |
dog.name // 'Sam' | |
dog.foodBowl // 'Empty' | |
function defaultProperties(target, fallback) { | |
return new Proxy(target, { | |
get(obj, prop) { | |
return prop in obj | |
? obj[prop] | |
: fallback; | |
} | |
}) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment