Why isn't Error's stack property included in Object.keys?

后端 未结 1 1481
被撕碎了的回忆
被撕碎了的回忆 2020-12-21 21:10

env: nodejs 8.1.5, also tested on jscomplete with same results

const error = new Error(\"message\");
const { message, ...rest } = error;
const keys = Object.         


        
相关标签:
1条回答
  • 2020-12-21 21:49

    It's not enumerable, so it won't be included in Object.keys or a for..in iteration:

    const error = new Error("message");
    // For Chrome, it's directly on the object:
    console.log(Object.getOwnPropertyDescriptor(error, 'stack'));
    // For Firefox, it's a getter on the prototype:
    console.log(Object.getOwnPropertyDescriptor(Object.getPrototypeOf(error), 'stack'));

    To iterate over all properties, including non-enumerable ones, use Object.getOwnPropertyNames instead:

    // Chrome:
    const error = new Error("message");
    Object.getOwnPropertyNames(error).forEach((propName) => {
      console.log(propName);
    });

    On Firefox, those two properties are getters on the prototype, rather than being directly on the error object. (The prototype also has other properties other than stack and message)

    // Chrome:
    const error = new Error("message");
    Object.getOwnPropertyNames(Object.getPrototypeOf(error)).forEach((propName) => {
      console.log(propName);
    });

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