Symbol.prototype.toString()

Symbol 值的 toString() 方法返回表示该符号值的字符串。

¥The toString() method of Symbol values returns a string representing this symbol value.

Try it

语法

¥Syntax

js
toString()

参数

¥Parameters

没有任何。

¥None.

返回值

¥Return value

表示指定符号值的字符串。

¥A string representing the specified symbol value.

描述

¥Description

Symbol 对象重写了 ObjecttoString 方法;它不继承 Object.prototype.toString()。对于 Symbol 值,toString 方法返回 "Symbol(description)" 形式的描述性字符串,其中 description 是符号的 description

¥The Symbol object overrides the toString method of Object; it does not inherit Object.prototype.toString(). For Symbol values, the toString method returns a descriptive string in the form "Symbol(description)", where description is the symbol's description.

toString() 方法要求其 this 值是 Symbol 基元或封装对象。它为其他 this 值抛出 TypeError,而不尝试将它们强制为符号值。

¥The toString() method requires its this value to be a Symbol primitive or wrapper object. It throws a TypeError for other this values without attempting to coerce them to symbol values.

因为 Symbol 有一个 [@@toPrimitive]() 方法,所以当 Symbol 对象是 强制为字符串 时,该方法始终优先于 toString()。但是,由于 Symbol.prototype[@@toPrimitive]() 返回符号基元,而符号基元在隐式转换为字符串时会抛出 TypeError,因此该语言永远不会隐式调用 toString() 方法。要对符号进行字符串化,你必须显式调用其 toString() 方法或使用 String() 函数。

¥Because Symbol has a [@@toPrimitive]() method, that method always takes priority over toString() when a Symbol object is coerced to a string. However, because Symbol.prototype[@@toPrimitive]() returns a symbol primitive, and symbol primitives throw a TypeError when implicitly converted to a string, the toString() method is never implicitly called by the language. To stringify a symbol, you must explicitly call its toString() method or use the String() function.

示例

¥Examples

使用 toString()

¥Using toString()

js
Symbol("desc").toString(); // "Symbol(desc)"

// well-known symbols
Symbol.iterator.toString(); // "Symbol(Symbol.iterator)"

// global symbols
Symbol.for("foo").toString(); // "Symbol(foo)"

隐式调用 toString()

¥Implicitly calling toString()

让 JavaScript 在符号封装对象上隐式调用 toString() 而不是 [@@toPrimitive]() 的唯一方法是首先通过 deleting@@toPrimitive 方法。

¥The only way to make JavaScript implicitly call toString() instead of [@@toPrimitive]() on a symbol wrapper object is by deleting the @@toPrimitive method first.

警告:在实践中你不应该这样做。除非你确切知道自己在做什么,否则永远不要改变内置对象。

¥Warning: You should not do this in practice. Never mutate built-in objects unless you know exactly what you're doing.

js
delete Symbol.prototype[Symbol.toPrimitive];
console.log(`${Object(Symbol("foo"))}`); // "Symbol(foo)"

规范

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

¥Specifications

浏览器兼容性

BCD tables only load in the browser

¥Browser compatibility

也可以看看