Why can't I see the keys of an Error object?

前端 未结 1 1790
一向
一向 2020-12-30 21:44

I am mystified by the fact that when I create a new Error object I can see its message or name, but I can\'t see a list of its keys by using the standard ways. Why is that?

相关标签:
1条回答
  • 2020-12-30 22:19

    JavaScript properties may be non-enumerable, which means they does not appear in for..in loops or Object.keys results.

    You can use Object.getOwnPropertyNames to get all properties (enumerable or non-enumerable) directly on an object. I say "directly" because normal enumeration looks up the object's prototype chain to get enumerable properties on parent prototypes, while getOwnPropertyNames does not.

    Thus, Object.getOwnPropertyNames(err) only shows

    ['stack',
     'arguments',
     'type',
     'message']
    

    The name property is a non-enumerable property of Error.prototype and is never set directly on an Error instance. (Prototyping recap: when you try to access err.name, the lookup err turns up nothing, so the interpreter looks at Error.prototype, which does have a name property.)

    0 讨论(0)
提交回复
热议问题