Benefits of the ES6 Reflect API

I am working on updating code to use ES6 syntax. I had the following line of code:

delete this._foo;

and my linter raised a sentence:

Reflect.deleteProperty(this, '_foo');

You can find the documentation for this method here .

The MDN docs indicate:

The Reflect.deleteProperty method allows you to delete a property on an object. It returns a boolean value indicating whether the property has been successfully deleted. It is almost identical to lax delete.

I understand that the delete keyword does not return a value indicating success, but it is much less verbose.

If I am not dependent on the success / failure of delete , is there any reason to approve Reflect.deleteProperty ? What does it mean that delete is non-strict?

I feel that many uses of the Reflect API are designed to resolve exceptional cases and / or provide a better conditional flow, but at the cost of a much more detailed statement. I am wondering if there is any benefit to using the Reflect API if I am not experiencing any problems with my current customs.

+6
source share
1 answer

Reflect API provides abstract operations, remaining behind JavaScript idioms. The primary purpose is to provide a reasonable way to redirect actions caused by Proxy traps . All Reflect methods correspond to the signature of proxy traps with the same name, so you can use new Proxy(target, Reflect) to create an object with identical behavior as the target object - everything will be redirected, including special JavaScript quirks.

This is especially important for getters and prototypes, since the third argument to many methods is the "receiver"

This value is provided for the target call if a getter is encountered.

Consider the following code:

 var target = { get foo() { return this.bar; }, bar: 3 }; var handler = { get(target, propertyKey, receiver) { if (propertyKey === 'bar') return 2; console.log(Reflect.get(target, propertyKey, receiver)); // this in foo getter references Proxy instance; logs 2 console.log(target[propertyKey]); // this in foo getter references "target" - logs 3 } }; var obj = new Proxy(target, handler); 

When you write Proxy , you expect it to fully cover the target β€” and there is no idiomatic way to do this without Reflect .

In addition, operators as functions are convenient for programming a functional style.

+8
source

All Articles