Is there any significant difference between Reflect and Proxy?
From what is documented, it seems that they have pretty much the same capabilities, apart from:
If the list above sums up all the differences, then what is the rationale for having both?
When developers use Proxy, they don't have direct access to the original object which makes it a great tool for encapsulation. Reflect on the other hand, is a built-in object that provides methods for JavaScript operations that are interceptable.
Reflect is a built-in object that provides methods for interceptable JavaScript operations. The methods are the same as those of proxy handlers. Reflect is not a function object, so it's not constructible.
In JavaScript, proxies (proxy object) are used to wrap an object and redefine various operations into the object such as reading, insertion, validation, etc. Proxy allows you to add custom behavior to an object or a function.
A Proxy is a placeholder object that “traps” invocations and operations made to its target object which it can then passthrough, no-op, or handle more elegantly. It creates an undetectable barrier around the target object that redirects all operations to the handler object.
Reflect and Proxy have completely different purposes and different capabilities.
MDN describes Proxy in that way:
The
Proxy
object is used to define custom behavior for fundamental operations (e.g. property lookup, assignment, enumeration, function invocation, etc).
And Reflect in that way:
Reflect is a built-in object that provides methods for interceptable JavaScript operations. The methods are the same as those of proxy handlers.
I realize that you've probably already read that, so I'll use an example to explain it further.
Let's say you have an object:
const obj = {
a: 'foo',
b: 'bar',
};
You can access property a
using property accessor like that:
console.log(obj.a); // 'foo'
You can do the same using Reflect.get()
method:
console.log(Reflect.get(obj, 'a')); // 'foo'
You can also create a proxy of that object using the Proxy constructor. We'll use the get
handler for intercepting all property lookups.
const proxy = new Proxy(obj, {
get(target, property) {
return property in target ? target[property] : 'default';
},
});
Now using either property accessor or Reflect.get()
to get an undefined property results in string 'default'
:
console.log(proxy.c); // 'default'
console.log(Reflect.get(proxy, 'c')); // 'default'
Proxy and Reflect can work great together. You can for example create a Proxy with a no-op get
handler using Reflect:
new Proxy(obj, {
get: Reflect.get,
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With