handler.deleteProperty()
handler.deleteProperty()
方法是 [[Delete]]
对象内部方法 的陷阱,被 delete
运算符等操作使用。
¥The handler.deleteProperty()
method is a trap for the [[Delete]]
object internal method, which is used by operations such as the delete
operator.
Try it
语法
参数
返回值
¥Return value
deleteProperty()
方法必须返回一个 Boolean
,指示该属性是否已成功删除。其他值为 强制转换为布尔值。
¥The deleteProperty()
method must return a Boolean
indicating whether or not the property has been successfully deleted. Other values are coerced to booleans.
如果 [[Delete]]
内部方法返回 false
,则许多操作(包括 严格模式 中的 delete
运算符)会抛出 TypeError
。
¥Many operations, including the delete
operator when in strict mode, throw a TypeError
if the [[Delete]]
internal method returns false
.
描述
拦截
¥Interceptions
该陷阱可以拦截以下操作:
¥This trap can intercept these operations:
delete
运算符:delete proxy[foo]
和delete proxy.foo
Reflect.deleteProperty()
或调用 [[Delete]]
内部方法 的任何其他操作。
¥Or any other operation that invokes the [[Delete]]
internal method.
不变量
¥Invariants
如果处理程序定义违反以下不变量之一,则代理的 [[Delete]]
内部方法将抛出 TypeError
:
¥The proxy's [[Delete]]
internal method throws a TypeError
if the handler definition violates one of the following invariants:
- 如果某个属性是目标对象的不可配置自有属性,则不能将该属性报告为已删除。也就是说,如果
Reflect.getOwnPropertyDescriptor()
对target
上的属性返回configurable: false
,则陷阱必须返回一个假值。 - 如果某个属性是目标对象的自有属性,并且目标对象不可扩展,则不能将该属性报告为已删除。也就是说,如果
Reflect.isExtensible()
对target
返回false
,并且Reflect.getOwnPropertyDescriptor()
对target
上的属性返回一个属性描述符,则陷阱必须返回一个假值。
示例
捕获删除操作符
¥Trapping the delete operator
以下代码捕获 delete
运算符。
¥The following code traps the delete
operator.
const p = new Proxy(
{},
{
deleteProperty(target, prop) {
if (!(prop in target)) {
console.log(`property not found: ${prop}`);
return false;
}
delete target[prop];
console.log(`property removed: ${prop}`);
return true;
},
},
);
p.a = 10;
console.log("a" in p); // true
const result1 = delete p.a; // "property removed: a"
console.log(result1); // true
console.log("a" in p); // false
const result2 = delete p.a; // "property not found: a"
console.log(result2); // false
规范
Specification |
---|
ECMAScript Language Specification # sec-proxy-object-internal-methods-and-internal-slots-delete-p |
浏览器兼容性
BCD tables only load in the browser
也可以看看
¥See also