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

语法

¥Syntax

js
new Proxy(target, {
  deleteProperty(target, property) {
  }
});

参数

¥Parameters

以下参数传递给 deleteProperty() 方法。this 绑定到处理程序。

¥The following parameters are passed to the deleteProperty() method. this is bound to the handler.

target

目标对象。

property

要删除的属性的名称或 Symbol

返回值

¥Return value

deleteProperty() 方法必须返回一个布尔值,指示该属性是否已成功删除。

¥The deleteProperty() method must return a boolean value indicating whether or not the property has been successfully deleted.

描述

¥Description

拦截

¥Interceptions

该陷阱可以拦截以下操作:

¥This trap can intercept these operations:

或调用 [[Delete]] 内部方法 的任何其他操作。

¥Or any other operation that invokes the [[Delete]] internal method.

不变量

¥Invariants

如果违反以下不变量,则陷阱在调用时会抛出 TypeError

¥If the following invariants are violated, the trap throws a TypeError when invoked.

  • 如果某个属性作为目标对象的不可配置自有属性存在,则无法删除该属性。

示例

¥Examples

捕获删除操作符

¥Trapping the delete operator

以下代码捕获 delete 运算符。

¥The following code traps the delete operator.

js
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

¥Specifications

浏览器兼容性

BCD tables only load in the browser

¥Browser compatibility

也可以看看