Javascript - Collection Reflect


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, //  ww  w .j  ava2  s  .c om
    beer: 5 

// ["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 ww  . j  a  va 2s  .c  o  m*/
    beer: 5 

const restHandler = { 
    get: function(target, property) { 
        if (property === "beer") { 
            return undefined; 
        return Reflect.get(target, property); 

const restProxy = new Proxy(restaurant, restHandler); 

// undefined 

// 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 

// 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.

Related Topics