Error.prototype.toString()

概述

toString() 方法返回一个指定的错误对象(Error object)的字符串表示。

语法

e.toString();

描述

Error 对象覆盖了 Object.prototype.toString() 方法。该方法实现如下:(假定 ObjectString 没有被更改):

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"

规范

Specification
ECMAScript Language Specification
# sec-error.prototype.tostring

浏览器兼容性

BCD tables only load in the browser

相关链接