left-icon

ECMAScript 6 Succinctly®
by Matthew Duffield

Previous
Chapter

of
A
A
A

CHAPTER 16

Reflect API

Reflect API


The Reflect API provides a runtime-level meta-operations on objects. This is effectively the inverse of the Proxy API, and allows making calls corresponding to the same meta-operations as the proxy traps. The Reflect object is a static object. You cannot create an instance of it. Likewise, all of its methods are static. You may be thinking that we already had some reflection-like methods available in JavaScript, but the biggest difference is that Reflect provides more meaningful return values.

Consider the following example:

Code Listing: 208

let obj = {}, name = "matt", desc = "here we go";

try {

  Object.defineProperty(obj, name, desc);

  // worked.

} catch (e) {

  // error.

}

if (Reflect.defineProperty(obj, name, desc)) {

  // worked

} else {

  // error.

}

     

In the first part, we have a try/catch block, and we are using the Object.defineProperty method. In this example, this method only returns the first argument passed into it. However, looking at the Reflect.defineProperty method, we see that it returns a Boolean value, which is much more meaningful.

Let’s consider another example:

Code Listing: 209

let obj = { a: 1 };

Object.defineProperty(obj, "b", { value: 2 });

obj[Symbol("c")] = 3;

console.log(Reflect.ownKeys(obj)); // [ "a", "b", Symbol(c) ]

     

As you can see in this example, Reflect.ownKeys gives us both string and symbol-based keys.

The following are all the methods the Reflect object contains:

  • 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)
Scroll To Top
Disclaimer
DISCLAIMER: Web reader is currently in beta. Please report any issues through our support system. PDF and Kindle format files are also available for download.

Previous

Next



You are one step away from downloading ebooks from the Succinctly® series premier collection!
A confirmation has been sent to your email address. Please check and confirm your email subscription to complete the download.