gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 13:12:01 24 4
gpt4 key购买 nike

我是 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com