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
语法
参数
返回值
描述
拦截
¥Interceptions
该陷阱可以拦截以下操作:
¥This trap can intercept these operations:
in
运算符:foo in proxy
with
检查:with(proxy) { (foo); }
Reflect.has()
或调用 [[HasProperty]]
内部方法 的任何其他操作。
¥Or any other operation that invokes the [[HasProperty]]
internal method.
不变量
示例
捕获 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 |
浏览器兼容性
BCD tables only load in the browser
也可以看看
¥See also