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.apply(target, receiver, args)
Reflect.defineProperty(target, name, desc)
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
1 2 3 4 5
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
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
Where can I use Reflect now?