Reflect
is a global object in ES6 and later that provides the reflection API for JavaScript. Most strongly typed languages, such as Java, provide a reflection API which you can use to inspect and fine-tune the low-level structure of objects. Since JavaScript is a dynamic language, most of that functionality is already present in the language. However, Reflect
provides a more meaningful place for these functionalities.
Reflect
is not a function, so it is not callable (and it cannot be used with the new
operator). It is just a global object and all its methods are static methods.
The methods of Reflect
are the same methods that are available for ES6 proxies. However, proxies are not the subject of discussion in this post.
Here is a list of methods available from Reflect
global object:
defineProperty
getOwnPropertyDescriptor
getPrototypeOf
setPrototypeOf
preventExtensions
isExtensible
construct
apply
deleteProperty
has
ownKeys
get
set
Some of these methods are similar to the methods available on Object
and have similar functions, albeit sometimes a little different. For example, Reflect.defineProperty
has the same functionality as Object.defineProperty
, except that it returns a boolean indicating whether or not the operation was successful, whereas Object.defineProperty
returns the first argument as its return value.
Reflect.getOwnPropertyDescriptor
works in the same way as Object.getOwnPropertyDescriptor
.
Similarly, Reflect.getPrototypeOf
works in the same way as Object.getPrototypeOf
. However, for setPrototypeOf
, the return value is different. Object.setPrototypeOf
returns the given object, while Reflect.setPrototypeOf
returns a boolean value indicating whether or not the operation was successful.
Reflect.preventExtensions
works like Object.preventExtensions
, except that if the given argument is not an object, it throws a TypeError
. In the case of Object
, the argument is coerced to an object. The same situation exists with isExtensible
.
The rest of the methods will be discussed in future posts.
Related Posts
- JavaScript Basics: Object.create
- JavaScript Basics: Object.assign
- JavaScript Basics: Object.getPrototypeOf and Object.setPrototypeOf
- JavaScript Basics: Object.keys, Object.values, and Object.entries
- JavaScript Basics: Object.is
- JavaScript Basics: Object.prototype.hasOwnProperty
- JavaScript Basics: Object.preventExtensions and Object.isExtensible
- JavaScript Basics: Object.seal and Object.isSealed
- JavaScript Basics: Object.freeze and Object.isFrozen