Last active
August 12, 2021 16:07
-
-
Save rauschma/e966dc9b5338a99041ef to your computer and use it in GitHub Desktop.
Prevent getting of unknown properties via ES6 proxies
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
// 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