語法
js
toString()
引數
無。
返回值
一個表示指定 Error 物件的字串。
描述
Error 物件重寫了所有物件繼承的 Object.prototype.toString() 方法。其語義如下:
js
Error.prototype.toString = function () {
if (
this === null ||
(typeof this !== "object" && typeof this !== "function")
) {
throw new TypeError();
}
let name = this.name;
name = name === undefined ? "Error" : `${name}`;
let msg = this.message;
msg = msg === undefined ? "" : `${msg}`;
if (name === "") {
return msg;
}
if (msg === "") {
return name;
}
return `${name}: ${msg}`;
};
示例
使用 toString()
js
const e1 = new Error("fatal error");
console.log(e1.toString()); // "Error: fatal error"
const e2 = new Error("fatal error");
e2.name = undefined;
console.log(e2.toString()); // "Error: fatal error"
const e3 = new Error("fatal error");
e3.name = "";
console.log(e3.toString()); // "fatal error"
const e4 = new Error("fatal error");
e4.name = "";
e4.message = undefined;
console.log(e4.toString()); // ""
const e5 = new Error("fatal error");
e5.name = "hello";
e5.message = undefined;
console.log(e5.toString()); // "hello"
規範
| 規範 |
|---|
| ECMAScript® 2026 語言規範 # sec-error.prototype.tostring |
瀏覽器相容性
載入中…