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

Angular + React = Performance

Angular and performance. When you do a Google search of these two words together, what you get it most likely blog posts about fixing performance issues or ways to avoid pitfalls. Theres no hiding the fact that the not-so-secret secret... Continue →