String.prototype.toString()

String 值的 toString() 方法返回此字符串值。

¥The toString() method of String values returns this string value.

Try it

语法

¥Syntax

js
toString()

参数

¥Parameters

没有任何。

¥None.

返回值

¥Return value

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

¥A string representing the specified string value.

描述

¥Description

String 对象重写了 ObjecttoString 方法;它不继承 Object.prototype.toString()。对于 String 值,toString 方法返回字符串本身(如果它是基元)或 String 对象封装的字符串。它具有与 String.prototype.valueOf() 完全相同的实现。

¥The String object overrides the toString method of Object; it does not inherit Object.prototype.toString(). For String values, the toString method returns the string itself (if it's a primitive) or the string that the String object wraps. It has the exact same implementation as String.prototype.valueOf().

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

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

由于 String 没有 [@@toPrimitive]() 方法,因此当在需要字符串的上下文中(例如在 模板文字 中)使用 String 对象时,JavaScript 会自动调用 toString() 方法。但是,String 基元值不会将 toString() 方法咨询为 强制为字符串 — 因为它们已经是字符串,因此不执行任何转换。

¥Because String doesn't have a [@@toPrimitive]() method, JavaScript calls the toString() method automatically when a String object is used in a context expecting a string, such as in a template literal. However, String primitive values do not consult the toString() method to be coerced to strings — since they are already strings, no conversion is performed.

js
String.prototype.toString = () => "Overridden";
console.log(`${"foo"}`); // "foo"
console.log(`${new String("foo")}`); // "Overridden"

示例

¥Examples

使用 toString()

¥Using toString()

以下示例显示 String 对象的字符串值:

¥The following example displays the string value of a String object:

js
const x = new String("Hello world");

console.log(x.toString()); // "Hello world"

规范

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

¥Specifications

浏览器兼容性

BCD tables only load in the browser

¥Browser compatibility

也可以看看