Skip to content

Instantly share code, notes, and snippets.

@ryanlaws
Created May 2, 2019 13:17
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 ryanlaws/745bf1ce9b720ddd38597627113b157c to your computer and use it in GitHub Desktop.
Save ryanlaws/745bf1ce9b720ddd38597627113b157c to your computer and use it in GitHub Desktop.
{
const props = ['a', 'b', 'c'];
// Manufacture
const makeObj = (name) => {
const obj = {};
props.forEach(prop =>
Object.defineProperty(obj, prop, {
get: () => `this is ${name}'s ${prop}`
}));
return obj;
}
const child = makeObj('parent.child');
Object.defineProperty(child, 'name', { get() { return "child" } });
const parent = makeObj('parent');
Object.defineProperty(parent, 'child', { get() { return child } });
// Check non-proxied behavior
parent.a = "derp"
props.forEach(prop => console.log(`parent.${prop}:`, parent[prop]));
props.forEach(prop => console.log(`parent.child.${prop}:`, parent.child[prop]));
console.log('parent.child.name:', parent.child.name);
// Proxy
const handler = (key, value) => ({
get: (obj, prop) => {
if (prop === key) return value;
return obj[prop];
}
});
let childProxy = new Proxy(parent.child, handler('c', 'c OVERRULED!'));
childProxy = new Proxy(childProxy, handler('name', `mommy, wow, I'm a proxy now!`));
const parentProxy = new Proxy(parent, handler('child', childProxy));
// Check proxied behavior
console.log('parent.child.c :', parent.child.c);
console.log('parentProxy.child.c:', parentProxy.child.c);
console.log('parentProxy.child.name:', parentProxy.child.name);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment