Created
May 2, 2019 13:17
-
-
Save ryanlaws/745bf1ce9b720ddd38597627113b157c to your computer and use it in GitHub Desktop.
This file contains hidden or 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
{ | |
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