當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


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。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。