Skip to content

Instantly share code, notes, and snippets.

@scottshane
Last active January 28, 2018 12:11
Show Gist options
  • Save scottshane/47ad1358bf9d64c080b46fce1164cc0e to your computer and use it in GitHub Desktop.
Save scottshane/47ad1358bf9d64c080b46fce1164cc0e to your computer and use it in GitHub Desktop.
Proxy / Reflect Experiment
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