Skip to content

Instantly share code, notes, and snippets.

@DavidWells
Created February 8, 2022 01:00
Show Gist options
  • Save DavidWells/fab0159168bf29aac7e976035228a46d to your computer and use it in GitHub Desktop.
Save DavidWells/fab0159168bf29aac7e976035228a46d to your computer and use it in GitHub Desktop.
Set private object fields via JS proxy
// https://betterprogramming.pub/everything-you-should-know-about-javascript-proxy-67576f2e069e
function setPrivateField(obj, prefix = "_"){
return new Proxy(obj, {
has: (obj, prop) => {
if(typeof prop === "string" && prop.startsWith(prefix)){
return false
}
return prop in obj
},
ownKeys: obj => {
return Reflect.ownKeys(obj).filter(
prop => typeof prop !== "string" || !prop.startsWith(prefix)
)
},
get: (obj, prop) => {
if(typeof prop === "string" && prop.startsWith(prefix)){
return undefined
}
return obj[prop]
}
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment