📜  JavaScript handler has()方法

📅  最后修改于: 2020-10-25 09:17:58             🧑  作者: Mango

JavaScript handler.has()方法

handler.has()方法用于“隐藏”所需的任何属性。这是运算符的陷阱。如果要访问该属性,它将返回布尔值true;否则,如果原始对象中是否存在键,则返回false。

句法

has: function(target, prop)

参量

target:目标对象。

prop:要检查是否存在的属性。

返回值

返回一个布尔值。

浏览器支持

Chrome 49
Edge 12
Firefox 18
Opera 36

例子1

const x = { f:10 };
const proxy = new Proxy(x, {
  has: function(target, name) {
   document.writeln('in has');
     //expected output: in has
 return name in target;
  }
});
document.writeln('f' in proxy);
//expected output: true

输出:

in has true

例子2

var x={hoo:1}
var xyz = new Proxy(x,  {
  has: function(target, key) {
    if(key == "a") return false;
      return true;
    }
  }
)
var x= ("a" in xyz)    
var y = ("b" in xyz)    
document.write("a in d: " +x)
//expected output: a in d: false
document.write('
'); document.write("b in d: " +y) //expected output: b in d: true

输出:

a in d: false
b in d: true

例子3

var s={
  voo:1
}
var p = new Proxy(s, {
  has: function(target, prop) {
    document.writeln('called: ' + prop);
    return false;
  }
});
document.writeln('a' in p); 
//expected output:called: a false

输出:

called: a false