javascript - 为什么可以打印 try 和 catch 对象,但任何普通对象都不能

标签 javascript object

我是 JavaScript 的初学者,我正在研究 try 和 catch 错误处理技术,直到我注意到 catch 对象可以被打印,但任何普通对象都不能打印,

   try{
    throw new Error("Manually Thrown Exception");
    }
    catch(errHanlder){
    alert(errHanlder);  // it will give (ERROR:Manually Throw Exception)
    }
<小时/>

任何创建的对象都不是例如:

var obj={name:"User"};
alert(obj);   //it will give [object Object] 

为什么尽管它们的类型都是对象,但这种奇怪的行为是可能的

最佳答案

该对象拥有一个toString函数。

来自the MDN :

Every object has a toString() method that is automatically called when the object is to be represented as a text value or when an object is referred to in a manner in which a string is expected. By default, the toString() method is inherited by every object descended from Object. If this method is not overridden in a custom object, toString() returns "[object type]", where type is the object type.

对于错误,它是 this one .

它在 the ECMAScript standard 中定义:

enter image description here

您可以执行相同的操作,甚至无需在原型(prototype)级别进行定义:

 var obj = {name:"Albert", toString(){ return "User: " + this.name }};
 alert(obj);

关于javascript - 为什么可以打印 try 和 catch 对象,但任何普通对象都不能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41693202/

相关文章:

javascript - ReactTable 固定最后一行

android - Flutter:添加到 Hive 框中的对象的字段在应用重启后返回 null

Javascript 对象方法范围 - 方法失败

delphi - 如何释放接口(interface)对象 (Delphi 7)

java - 我无法引用我实例化的对象

javascript - IE8 控制台.log

javascript - 评估 js 函数参数内的表达式

javascript - React 中的回调函数问题

javascript - 如何通过文本框数组提交按钮

java - 数组中的不同对象