JavaScript
x
4
1
let x=new Error();
2
x.message="Hello";
3
Object.keys(x) //["message"]
4
The above makes absolute sense; message
is a property of x
instance of Error
JavaScript
1
5
1
let y=new Error("Morning");
2
y.message; //"Morning"
3
Object.keys(y) // []
4
Object.getPrototypeOf(y); // {name: "Error", message: "", constructor: ƒ, toString: ƒ}
5
The question is: Where does message exist if neither in the y instance itself nor in the prototype chain?
Advertisement
Answer
Object.keys
will only include own and enumerable properties. Now it happens that an Error
object inherits a non-enumerable property message
, so you don’t see it with Object.keys
, but it certainly is there.
You can list also non-enumerable properties with Object.getOwnPropertyNames
:
JavaScript
1
4
1
let y=new Error("Morning");
2
console.log(y.message); //"Morning"
3
console.log(Object.getOwnPropertyNames(y));
4
console.log(Object.getOwnPropertyDescriptors(y));