Error.prototype.toString() - JavaScript 编辑
概述
toString()
方法返回一个指定的错误对象(Error object)的字符串表示。
语法
e.toString();
描述
Error
对象覆盖了 Object.prototype.toString()
方法。该方法实现如下:(假定 Object
和 String
没有被更改):
Error.prototype.toString = function()
{
"use strict";
var obj = Object(this);
if (obj !== this)
throw new TypeError();
var name = this.name;
name = (name === undefined) ? "Error" : String(name);
var msg = this.message;
msg = (msg === undefined) ? "" : String(msg);
if (name === "")
return msg;
if (msg === "")
return name;
return name + ": " + msg;
};
示例
var e = new Error("fatal error");
print(e.toString()); // "Error: fatal error"
e.name = undefined;
print(e.toString()); // "Error: fatal error"
e.name = "";
print(e.toString()); // "fatal error"
e.message = undefined;
print(e.toString()); // "Error"
e.name = "hello";
print(e.toString()); // "hello"
规范
规范版本 | 规范状态 | 注解 |
---|---|---|
ECMAScript 1st Edition. | Standard | Initial definition. Implemented in JavaScript 1.1 |
ECMAScript 5.1 (ECMA-262) Error.prototype.toString | Standard | |
ECMAScript 2015 (6th Edition, ECMA-262) Error.prototype.toString | Standard |
浏览器兼容性
We're converting our compatibility data into a machine-readable JSON format. This compatibility table still uses the old format, because we haven't yet converted the data it contains. Find out how you can help!Feature | Chrome | Firefox (Gecko) | Internet Explorer | Opera | Safari |
---|---|---|---|---|---|
Basic support | (Yes) | (Yes) | (Yes) | (Yes) | (Yes) |
Feature | Android | Chrome for Android | Firefox Mobile (Gecko) | IE Mobile | Opera Mobile | Safari Mobile |
---|---|---|---|---|---|---|
Basic support | (Yes) | (Yes) | (Yes) | (Yes) | (Yes) | (Yes) |
相关链接
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论