Skip to content

Instantly share code, notes, and snippets.

@iainjreid
Created February 17, 2020 21:43
Show Gist options
  • Save iainjreid/8c262c52096e120432c508f46229c67b to your computer and use it in GitHub Desktop.
Save iainjreid/8c262c52096e120432c508f46229c67b to your computer and use it in GitHub Desktop.
Default properties using a JavaScript Proxy
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