Last active
June 21, 2018 12:38
-
-
Save cyrilf/ab6ffe82eaf9f75f7f473641ab48af68 to your computer and use it in GitHub Desktop.
Proxy
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
// From: https://stackoverflow.com/questions/50963215/can-we-specify-a-generic-getter-on-an-object-in-javascript | |
// Allows you to access nested property (1 level) without the need to to safety check | |
const properties = { email: { title: "Email", value: "[email protected]" } } | |
const proxy = new Proxy(properties, { | |
get: (target, prop) => (prop in target) ? target[prop] : {}, | |
}) | |
// or | |
const proxy = new Proxy(properties, { | |
get: (target, prop) => { | |
if (prop in target) { | |
let ret = Reflect.get(target, prop) | |
if (typeof ret === "function") { | |
ret = ret.bind(target) | |
} | |
return ret | |
} | |
return {} | |
}, | |
}) | |
proxy.email.value === "[email protected]" // true | |
properties.unknownProp.value === Error // cannot read `value` of undefined | |
properties.unknownProp && properties.unknownProp.value === undefined // true / it works but long to write.. | |
proxy.unknownProp.value === undefined // true / short, clean & safe |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment