简体   繁体   中英

Why the message and stack properties of an error object are not enumerable

const myError = new Error("bug");
myError.propertyIsEnumerable("message") //false
myError.propertyIsEnumerable("stack") //false

The implications of this are that when you for loop this kind of object, you won't fetch these fields, which I find strange.

What was the reasoning behind that?

The reason that I can think of is to maintain the behaviour of Object.keys . If you see the initial specs, the error part not very detailed. the error specs are

This specification specifies the last possible moment an error occurs. A given implementation may generate errors
sooner (e.g. at compile-time). Doing so may cause differences in behavior among implementations. Notably, if runtime
errors become catchable in future versions, a given error would not be catchable if an implementation generates the
error at compile-time rather than runtime.
An ECMAScript compiler should detect errors at compile time in all code presented to it, even code that detailed
analysis might prove to be “dead” (never executed). A programmer should not rely on the trick of placing code within
an if (false) statement, for example, to try to suppress compile-time error detection.
In general, if a compiler can prove that a construct cannot execute without error under any circumstances, then it may
issue a compile-time error even though the construct might neverbe executed at all.

You can see the first specs at https://www.ecma-international.org/publications/files/ECMA-ST-ARCH/ECMA-262,%201st%20edition,%20June%201997.pdf

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