Skip to content
Advertisement

Prototypal Inheritance: where to find the message property of Error instance?

let x=new Error();
x.message="Hello";
Object.keys(x) //["message"]

The above makes absolute sense; message is a property of x instance of Error

let y=new Error("Morning");
y.message;   //"Morning"
Object.keys(y) // []
Object.getPrototypeOf(y);  // {name: "Error", message: "", constructor: ƒ, toString: ƒ}

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:

let y=new Error("Morning");
console.log(y.message);   //"Morning"
console.log(Object.getOwnPropertyNames(y)); 
console.log(Object.getOwnPropertyDescriptors(y)); 
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement