handler.has()

handler.has() 方法是 [[HasProperty]] 对象内部方法 的陷阱,被 in 运算符等操作使用。

¥The handler.has() method is a trap for the [[HasProperty]] object internal method, which is used by operations such as the in operator.

Try it

语法

¥Syntax

js
new Proxy(target, {
  has(target, prop) {
  }
});

参数

¥Parameters

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

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

target

目标对象。

prop

要检查是否存在的属性的名称或 Symbol

返回值

¥Return value

has() 方法必须返回布尔值。

¥The has() method must return a boolean value.

描述

¥Description

拦截

¥Interceptions

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

¥This trap can intercept these operations:

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

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

不变量

¥Invariants

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

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

  • 如果属性作为目标对象的不可配置自有属性存在,则不能将其报告为不存在。
  • 如果属性作为目标对象自己的属性存在并且目标对象不可扩展,则不能将其报告为不存在。

示例

¥Examples

捕获 in 运算符

¥Trapping the in operator

以下代码捕获 in 运算符。

¥The following code traps the in operator.

js
const p = new Proxy(
  {},
  {
    has(target, prop) {
      console.log(`called: ${prop}`);
      return true;
    },
  },
);

console.log("a" in p);
// "called: a"
// true

以下代码违反了不变量。

¥The following code violates an invariant.

js
const obj = { a: 10 };
Object.preventExtensions(obj);

const p = new Proxy(obj, {
  has(target, prop) {
    return false;
  },
});

"a" in p; // TypeError is thrown

规范

Specification
ECMAScript Language Specification
# sec-proxy-object-internal-methods-and-internal-slots-hasproperty-p

¥Specifications

浏览器兼容性

BCD tables only load in the browser

¥Browser compatibility

也可以看看