handler.has() 方法可以看作是针对 in 操作的钩子.

Syntax

var p = new Proxy(target, {
  has: function(target, prop) {
  }
});

Parameters

下面是传递给 has 方法的参数. this is bound to the handler.

target
目标对象.
prop
需要检查是否存在的属性.

Return value

has 方法返回一个 boolean 属性的值.

Description

handler.has 方法可以看作是针对 in 操作的钩子.

Interceptions

这个钩子可以拦截下面这些操作:

Invariants

如果违反了下面这些规则,  proxy 将会抛出 TypeError:

Examples

下面的代码 hook 了 in 操作.

var p = new Proxy({}, {
  has: function(target, prop) {
    console.log('called: ' + prop);
    return true;
  }
});

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

下面的代码违反了规则.

var obj = { a: 10 };
Object.preventExtensions(obj);
var p = new Proxy(obj, {
  has: function(target, prop) {
    return false;
  }
});

'a' in p; // TypeError is thrown

Specifications

Specification Status Comment
ECMAScript 2015 (6th Edition, ECMA-262)
[[HasProperty]]
Standard Initial definition.
ECMAScript Latest Draft (ECMA-262)
[[HasProperty]]
Draft  

Browser compatibility

We're converting our compatibility data into a machine-readable JSON format. This compatibility table still uses the old format, because we haven't yet converted the data it contains. Find out how you can help!
Feature Chrome Firefox (Gecko) Internet Explorer Opera Safari
Basic support ? 18 (18) ? ? ?
Feature Android Chrome for Android Firefox Mobile (Gecko) IE Mobile Opera Mobile Safari Mobile
Basic support ? ? 18.0 (18) ? ? ?

See also