Skip to content

Instantly share code, notes, and snippets.

@ealush
Created February 21, 2018 11:48
Show Gist options
  • Select an option

  • Save ealush/8fa4cc23a4543dce7b3f3b1a2e780dec to your computer and use it in GitHub Desktop.

Select an option

Save ealush/8fa4cc23a4543dce7b3f3b1a2e780dec to your computer and use it in GitHub Desktop.
Simple proxy getter example
// Le'ts start with this object
const orig = {
a: 'get',
b: 'moving'
};
// Now let's write a handler that serves as a getter for our object.
const handler = {
// by setting the `get` function we say that we intend to
// intercept `get` interactions with the object
// it accepts target (the original object) and key (the accessed property)
get: (target, key) => {
if (key === 'b') {
// if key === 'b' > instead of returning the original value
// we return `schwifty`
return 'schwifty';
} else if (target.hasOwnProperty(key)) {
// if the original object has the property we're looking for
// simply return it
return target[key];
} else {
// else, log an error
console.error('Could not find what you are looking for');
}
}
};
const proxy = new Proxy(orig, handler);
// Here are the differences between the original object and the proxy object:
console.log(`${orig.a} ${orig.b}`);
// get moving
console.log(`${proxy.a} ${proxy.b}`);
// get schwifty
orig.c
// undefined
proxy.c
// Could not find what you are looking for
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment