Reflect is a built-in global object that provides introspection methods.
These methods gather information about the runtime-level meta-operations on objects.
const restaurant = { soda: 10, /* www . j a v a 2 s .com*/ beer: 5 }; console.log(Reflect.ownKeys(restaurant)); // ["soda", "beer"]
Reflect is a static object and cannot be used with the new keyword.
For every trap method in ES6 Proxy, there is a matching reflection method available in Reflect.
Reflect is useful for implementing traps in proxies.
The following code are using Reflect with Proxy:
const restaurant = { soda: 2, // w w w . j a v a2s .com beer: 5 }; const restHandler = { get: function(target, property) { if (property === "beer") { return undefined; } return Reflect.get(target, property); } }; const restProxy = new Proxy(restaurant, restHandler); console.log(restProxy.beer); // undefined console.log(restProxy.soda); // 2
Here, we are preventing the access to beer and using Reflect.get() to access other properties of the target object.
If Reflect.get is used on a non-object target, it will throw an error, whereas target[property] would return undefined.
It is a good practice to use Reflect.get here.
The following code are trying to get a property on a non-object target:
console.log(Reflect.get(1, "name")); // TypeError: Reflect.get called on non-object console.log(1["name"]); // undefined
Some common useful method from Reflect:
Method | Description |
---|---|
Reflect.get() | A function that returns the value of properties. |
Reflect.set() | A function that assigns values to properties. Returns a Boolean that is true if the update was successful. |
Reflect.getPrototypeOf() | Same as Object.getPrototypeOf(). |
Reflect.has() | The in operator as function. Returns a Boolean indicating whether an own or inherited property exists. |