当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


JavaScript handler.ownKeys()用法及代码示例


JavaScript 的 handler.ownKeys() 方法用于返回一个可枚举对象。此方法是 Reflect.ownKeys() 的陷阱。

用法

ownKeys:function(target)

参数

target:目标对象。

返回值

返回一个可枚举的对象。

浏览器支持

Chrome 49
Edge 12
Firefox 18
Opera 36

例子1

<script>
var proxy1 = new Proxy({}, {
  ownKeys:function(target) {
   document.writeln(" Use handler.ownKeys() is ");
    return ['a', 'b', 'c'];
  }
});
document.writeln(Object.getOwnPropertyNames(proxy1)); 
//expected output:Use handler.ownKeys() is a,b,c
</script>

输出:

Use handler.ownKeys() is a,b,c

例子2

<script>
var x = {
 Age:24,
 Count:45
}
var y = {
  ownKeys (target) {
    return Reflect.ownKeys(target)
  }
}
var z = new Proxy(x,y);
for (let key of Object.keys(z)) 
{
  document.writeln(key);
  // expected output:Age Count
 }
</script>

输出:

Age Count 

例子3

<script>
var x = { foo:1 };
Object.defineProperty(x, 'variable', { value:2, 
                                  writable:true,
                                enumerable:false,
                                  configurable:true } );

var proxy = new Proxy(x, {
  ownKeys:function(target, a, b) {
    document.writeln('in ownKeys method');
var names = Object.getOwnPropertyNames(target);
    //Useing Object.getOwnProperty mehod.
    var symbols = Object.getOwnPropertySymbols(target);
    return names.concat(symbols);
  }
});
document.writeln(Object.keys(proxy));
//expected.output:in ownKeys method foo 
document.writeln("<br/>")
document.writeln(Object.getOwnPropertyNames(proxy));
//expected output:in ownKeys method foo,variable
</script>

输出:

in ownKeys method foo 
in ownKeys method foo,variable






相关用法


注:本文由纯净天空筛选整理自 JavaScript handler.ownKeys() Method。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。