Hemanth.HM

A Computer Polyglot, CLI + WEB ♥'r.

ES6 Reflect API

| Comments

What is the reflect object all about?

ES6's Reflect object is a single ordinary object that contains methods related to Ecmascript 6 reflection API.

The below are some key points that one must be aware of before using them.

  • It's not a function object.

  • It does not have a [[Construct]] internal method. (Can't use new)

  • It does not does not have a [[Call]] internal method. (Can't invoke it as a function)

What are all the methods that Reflect object has?

  • Reflect.get(target, name, [receiver])

  • Reflect.set(target, name, value, [receiver])

  • Reflect.has(target, name)

  • Reflect.apply(target, receiver, args)

  • Reflect.construct(target, args)

  • Reflect.getOwnPropertyDescriptor(target, name)

  • Reflect.defineProperty(target, name, desc)

  • Reflect.getPrototypeOf(target)

  • Reflect.setPrototypeOf(target, newProto)

  • Reflect.deleteProperty(target, name)

  • Reflect.enumerate(target)

  • Reflect.preventExtensions(target)

  • Reflect.isExtensible(target)

  • Reflect.ownKeys(target)

Why reflect?

The above list, looks very familiar to the methods defined in Object but on of the major difference is that the Reflect object's method does return meaningful data rather than throwing an error in case of failure.

Let's see few examples to understand more about it:

1
2
3
4
5
6
try {
  Object.defineProperty(obj, name, desc);
  // worked.
} catch (e) {
  // bombed.
}

With reflect:

1
2
3
4
5
if (Reflect.defineProperty(obj, name, desc)) {
  // worked
} else {
  // bombed
}

Same structure applies for:

  • Reflect.set (to update a property).

  • Reflect.deleteProperty (to delete a property).

  • Reflect.preventExtensions (to make an object non-extensible).

  • Reflect.setPrototypeOf (to update an object's prototype link).

Reflect.has(obj, name) equivalent of (name in obj) and Reflect.deleteProperty(obj, name) equivalent to delete obj[name], but both of these reflect APIs are first-class functions.

We would use apply method on a function fn with a variable number of arguments packed as an array args and binding the this value to an obj as fn.apply(obj, args) but if fn has defined it's own apply method we need to invoke Function.prototype.apply.call(fn, obj, args) to make sure that built-in is invoked, but the same can be simplified to Reflect.apply(fn, obj, args)

Proxy and Reflect gel well:

There is a one-to-one correspondence between "reflect" methods and Proxy traps which ensures that the return type to be compatible with the return type of the Proxy traps.

1
2
3
4
5
var life = Proxy.create({
  get: function(target, name, receiver) {
    return Reflect.get(target, name, receiver);
  }
});

Where can I use Reflect now?

As of now you can use this in IE Technical Preview or use polyfills like echo-js or harmony-reflect

References:

Comments