Skip to content

Instantly share code, notes, and snippets.

@jakub-g
Last active October 9, 2019 14:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jakub-g/b7c76659ca22373a6f1d6d02feb3fd18 to your computer and use it in GitHub Desktop.
Save jakub-g/b7c76659ca22373a6f1d6d02feb3fd18 to your computer and use it in GitHub Desktop.
Proxying reads from global variables via ES6 proxy and `with`
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<script>
var windowProxy = new Proxy(window, {
get: function(target, propKey, value) {
if (typeof propKey !== 'symbol') {
debugger
console.log('getting window.' + propKey);
console.log(new Error().stack);
}
return Reflect.get(target, propKey);
},
set: function(target, propKey, value, receiver) {
debugger
console.log('setting ' + propKey + ' to ' + value);
return Reflect.set(target, propKey, value, receiver);
}
});
with(windowProxy) {
whatever = 42; // not trapped via setter, even if the value is correctly set
let local = whatever; // trapped via getter
}
windowProxy.whatever = 84; // trapped via setter
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment