blob: 2dfc20c9375aa15491688ac06e02d6300bee6418 (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
|
---
title: Error.prototype.toString()
slug: Web/JavaScript/Reference/Global_Objects/Error/toString
translation_of: Web/JavaScript/Reference/Global_Objects/Error/toString
---
<div>
{{JSRef("Global_Objects", "Error", "EvalError,InternalError,RangeError,ReferenceError,SyntaxError,TypeError,URIError")}}</div>
<h2 id="Summary">概述</h2>
<p><code><strong>toString()</strong></code> 方法返回一个指定的错误对象(Error object)的字符串表示。</p>
<h2 id="Syntax">语法</h2>
<pre class="syntaxbox"><code><em>e</em>.toString();</code></pre>
<h2 id="Description">描述</h2>
<p>{{jsxref("Error")}} 对象覆盖了 {{jsxref("Object.prototype.toString()")}} 方法。该方法实现如下:(假定 <code>Object</code> 和 <code>String</code> 没有被更改):</p>
<pre class="brush:js">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;
};
</pre>
<h2 id="Example">示例</h2>
<pre class="brush:js">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"
</pre>
<h2 id="规范">规范</h2>
{{Specifications}}
<h2 id="浏览器兼容性">浏览器兼容性</h2>
{{Compat}}
<h2 id="See_also">相关链接</h2>
<ul>
<li>{{jsxref("Error.prototype.toSource()")}}</li>
</ul>
|