我一直致力于升级一些代码以使用 ES6 语法。我有以下代码行:
delete 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
关键字不会返回指示成功的值,但它更简洁。
如果我不依赖于 delete
的成功/失败,还有什么理由支持 Reflect.deleteProperty
? delete
是非严格的是什么意思?
我觉得 Reflect
API 的很多用例都是为了解决异常情况和/或提供更好的条件流,但代价是语句更加冗长。我想知道如果我当前的使用没有遇到任何问题,使用 Reflect
API 是否有任何好处。
最佳答案
Reflect
API 公开了隐藏在常见 JavaScript 习语后面的抽象操作。 它的主要用途是提供合理的方式来转发在 Proxy
陷阱上调用的操作。所有 Reflect
方法都匹配同名代理陷阱的签名,因此您可以使用 new Proxy(target, Reflect)
创建与 target 具有相同行为的对象
对象 - 一切都将被转发,包括特殊的 JavaScript 怪癖。
这对于 getter 和原型(prototype)尤为重要,如 third argument of many methods is "receiver"
The value of
this
provided 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, 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);
当您编写 Proxy
时,您希望它完全覆盖目标对象 - 如果没有 Reflect
,就没有惯用的方法可以做到这一点。
此外,将运算符作为函数可以方便地进行函数式编程。
关于javascript - ES6 Reflect API 的好处,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35276559/