我正在尝试学习JS并且对对象属性感到困惑,在下面的示例中,我使用了未定义的函数来生成错误,并且我试图获取错误对象的属性和方法。虽然e.message确实打印了错误消息,但我无法将消息作为错误对象属性。这里发生了什么?
try{
unknownFunction();// undefined function here
}catch(e){
console.log(e); // it is ReferenceError
console.log(e.message);//message
console.log(typeof e); // object
console.log(e instanceof ReferenceError); // true
console.log(e === ReferenceError); // false
for(var propertyName in e) {
console.log("Name "+propertyName+" and Value "+e[propertyName]);
} // []
let allKeys = Object.keys(e);
console.log(allKeys);// []
let fnKeys = allKeys.filter(key => typeof myObj[key] == 'function');
console.log(fnKeys); // []
}
答案 0 :(得分:2)
message
根本不是enumerable property:
try{
unknownFunction();// undefined function here
}catch(e){
console.log( Object.getOwnPropertyDescriptor( e, 'message' ) )
/* {
value: "unknownFunction is not defined",
writable: true,
enumerable: false,
configurable: true
} */
let allKeys = Object.getOwnPropertyNames(e);
console.log(allKeys);
// ["stack","message"]
}