ES6 Reflect API

This is the part of a series of blogs on the new features on the upcoming ECMAScript 6 (ES6) specification which JavaScript implements.

In this blog we focus on the Reflect API introduced in ES6.

Reflect Object #

What is the Reflect API? It starts with the Reflect Object which is a single ordinary object that is bound to the global scope. As with other special objects, the Reflect Object is not a function object and does not have a construct or call internal methods nor can you new it. The Reflect Object merely allows us to use the Reflect API which is the ES6 way of updating an object’s prototype avoiding the legacy __proto__.

Reflect API #

The API contains multiple methods which can be best described by the doc. It is pointless for me to reiterate the methods, a more interesting take is the usage of the Reflect API.

Use Case #

If you went to the link above, you would notice that the Reflect object’s methods is very similar to that of methods of the Object. The Reflect object however shields the user from self-destructing their code if an error is present.

ES5 Object

try {
  Object.defineProperty(obj, name, desc);
  // working!
} catch {
  // sad situation
}

ES6 Reflect Object

if (Reflect.defineProperty(obj, name, desc)) {
  // working!
} else {
  // sad situation
}

Differences with Object #

There is only mainly two differences in use cases.

Use in Proxy #

The reflect API is very well suited and actually even made for ES6 Proxy traps which ensure that the return type of a Reflect method is the same as the expected return type of a Proxy trap. There is a one-to-one mapping to it.

var harrypotter = Proxy.create({
  get: function(target, name, receiver) {
    return Reflect.get(target, name, receiver);
  }
});

However the ES6 Proxy is out of scope for this blog so we’ll end it with that.

 
5
Kudos
 
5
Kudos

Now read this

Push Notifications on Java EE 5

This is a way to have “server push” notifications to the client’s browser without having AsyncContext available. With a distributed network system, you can’t just store notification messages into the cache and retrieve it quickly by... Continue →