-
-
Save caracal7/2315797d75e14b10ab6a76cacda1829b to your computer and use it in GitHub Desktop.
Proxy / Reflect Experiment
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
var targetObject = { | |
sayHi(){ return `returning show: ${p.show}` }, | |
show: 'family guy', | |
characters: { | |
dad: 'peter', | |
mom: 'lois', | |
daughter: 'meg', | |
son: 'chris', | |
baby: 'stewie', | |
dog: 'brian' | |
} | |
}; | |
var proxy_handler = { | |
/* get trap*/ get(target, key, receiver) { | |
// if 'set` is on a nested object property of the targetObject | |
// `get` is called so if a nested obect property is found add | |
// a new proxy to it. | |
if(typeof target[key] === 'object' && target[key] !== null ) { | |
console.log("found object and not null") | |
return new Proxy(target[key], proxy_handler); | |
} else { | |
console.log('already proxied') | |
return Reflect.get(target, key); /* get can return anything */ | |
} | |
}, | |
/* set trap */ set(target, key, value, receiver){ | |
Reflect.set(target, key, value); | |
console.log("set: ", target[key]); | |
return true; /* set must return bool */ | |
} | |
} | |
var p = new Proxy(targetObject, proxy_handler) | |
// USAGE | |
/* set */ p.show = 'some new value' | |
/* get */ p.show |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment