Skip to content

Instantly share code, notes, and snippets.

@rauschma
Last active August 12, 2021 16:07
Show Gist options
  • Save rauschma/e966dc9b5338a99041ef to your computer and use it in GitHub Desktop.
Save rauschma/e966dc9b5338a99041ef to your computer and use it in GitHub Desktop.
Prevent getting of unknown properties via ES6 proxies
// The following code is valid ECMAScript 6, but doesn’t work in Firefox, yet
function PreventUnknownGet() {
}
PreventUnknownGet.prototype = new Proxy(Object.prototype, {
get(target, propertyKey, receiver) {
if (!(propertyKey in target)) {
throw new TypeError('Unknown property: '+propertyKey);
}
// Make sure we don’t block access to Object.prototype
return Reflect.get(target, propertyKey, receiver);
}
});
class Point extends PreventUnknownGet {
constructor(x, y) {
this.x = x;
this.y = y;
}
}
var p = new Point(5, 7);
console.log(p.x); // 5
console.log(p.z); // TypeError
// Alternative: wrap proxy around `this`
// Prevent _creation_ of unknown properties via non-extensibility
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment