CHAPTER 16
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: