javascript - Benefits of ES6 Reflect API -
i've been working on upgrading code use es6 syntax. had following line of code:
delete this._foo;
and linter raised suggestion use:
reflect.deleteproperty(this, '_foo');
you can find documentation method here.
the mdn docs state:
the reflect.deleteproperty method allows delete property on object. returns boolean indicating whether or not property deleted. identical non-strict delete operator.
i understand delete
keyword not return value indicating success, less verbose.
if i'm not dependent on success/failure of delete
there reason favor reflect.deleteproperty
? mean delete
non-strict?
i feel lot of use cases reflect
api resolving exceptional cases and/or providing better conditional flow, @ cost of more verbose statement. i'm wondering if there's benefit use reflect
api if i'm not experiencing issues current usages.
reflect
api exposes abstract operations staying behind common javascript idioms. it's main use provide reasonable way forward actions called on proxy
traps. of reflect
methods match signature of proxy traps same name, can use new proxy(target, reflect)
create object identical behaviour target
object - forwarded, including special javascript quirks.
it's important getters , prototypes, third argument of many methods "receiver"
the value of
this
provided call target if getter encountered.
consider following code:
var target = { foo() { return this.bar; }, bar: 3 }; var handler = { get(target, propertykey, receiver) { if (propertykey === 'bar') return 2; console.log(reflect.get(target, propertykey, receiver)); // in foo getter references proxy instance; logs 2 console.log(target[propertykey]); // in foo getter references "target" - logs 3 } }; var obj = new proxy(target, handler);
when write proxy
, expect cover target object - , there no idiomatic way without reflect
.
moreover, having operators functions convenient functional style programming.
Comments
Post a Comment