简体   繁体   中英

Why passing function object to Object.keys() returns empty array?

So, functions in js are objects with some keys, right? I'm trying to iterate through them, but i'm getting empty list:

function f(a) {
console.log(Object.keys(f)) //prints []
console.log(f.arguments) //key "arguments" exists and prints Arguments object
}

Any expanation why Object.keys() doesn't return keys for function object?

Object.keys will only list enumerable properties. The arguments property is not enumerable, as you can see if you use getOwnPropertyDescriptor .

The property exists, but

 function f() { } console.log(Object.getOwnPropertyDescriptor(f, 'arguments'));

To get a list of all own-property keys (excluding symbols), including non-enumerable ones, you can use Object.getOwnPropertyNames .

 function f() { } console.log(Object.getOwnPropertyNames(f));

which, here, gives you

[
  "length",
  "name",
  "arguments",
  "caller",
  "prototype"
]

Object.keys could have returned properties if any properties put directly on the function were enumerable, such as

 function f() { } f.someProp = 'foo'; console.log(Object.keys(f));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM