Javascript错误对象属性

时间:2017-01-16 04:25:11

标签: javascript properties ecmascript-6

我正在尝试学习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); // []
}

1 个答案:

答案 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"]

}