Skip to content

Instantly share code, notes, and snippets.

@prof3ssorSt3v3
Created September 27, 2020 19:01
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save prof3ssorSt3v3/3091232234ec7816eb738272562b7dc4 to your computer and use it in GitHub Desktop.
Save prof3ssorSt3v3/3091232234ec7816eb738272562b7dc4 to your computer and use it in GitHub Desktop.
How to use the Reflect object in JavaScript to intercept JS object operations
// Reflect Object - built-in object that provides methods for interceptable JavaScript operations
// All methods are static
// has no constructor cannot use `new`
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Reflect
const log = console.log;
let alex = {
name: 'Alex',
id: 93,
hello: function (a, b) {
console.log(`Hello my name is ${this.name}. ${a} ${b}`);
},
};
log(Reflect.ownKeys(alex));
log(Reflect.get(alex, 'id'));
log(Reflect.set(alex, 'id', 94));
log(Reflect.get(alex, 'id'));
log(Reflect.has(alex, 'name'));
Reflect.apply(alex.hello, alex, Reflect.ownKeys(alex));
Reflect.defineProperty(alex, 'age', { value: 30, enumerable: false });
log(Reflect.get(alex, 'age'));
/**
Reflect.apply(targetFunc, thisArg, argList); //for functions
Reflect.get(target, key, handler); //handler is Proxy. get the value of a property
Reflect.set(target, key, value, handler); //handler is Proxy. set the value of a property
Reflect.has(target, key); // check if it has a property
Reflect.delete(target, key); //like the delete operator
Reflect.ownKeys(target); // enumerate through the properties
Reflect.defineProperty(target, key, {propertyDescriptor}); //like Object.defineProperty
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment