删除this._foo;
我的linter提出了使用建议:
Reflect.deleteProperty(this,’_ foo’);
您可以找到此方法here的文档.
MDN文档指出:
The Reflect.deleteProperty method allows you to delete a property on
an object. It returns a Boolean indicating whether or not the property
was successfully deleted. It is almost identical to the non-strict
delete operator.
我知道delete关键字不会返回一个表示成功的值,但它更简洁.
如果我不依赖删除的成功/失败,是否有理由支持Reflect.deleteProperty?删除是非严格的是什么意思?
我觉得Reflect API的很多用例都是用于解决异常情况和/或提供更好的条件流,但代价是更冗长的语句.我想知道如果我没有遇到任何与当前用法有关的问题,使用Reflect API是否有任何好处.
解决方法
这对于吸气剂和原型来说尤其重要,如third argument of many methods is “receiver”
The value of
thisprovided for the call to target if a getter is encountered.
考虑以下代码:
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,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);
当您编写代理时,您希望它完全覆盖目标对象 – 并且没有Reflect就没有惯用的方法来执行此操作.
此外,将操作符作为函数可以方便地进行功能样式编程.