Movatterモバイル変換


[0]ホーム

URL:


  1. 面向开发者的 Web 技术
  2. JavaScript
  3. JavaScript 参考
  4. JavaScript 标准内置对象
  5. String
  6. String.prototype.toString()

此页面由社区从英文翻译而来。了解更多并加入 MDN Web Docs 社区。

View in EnglishAlways switch to English

String.prototype.toString()

Baseline Widely available

This feature is well established and works across many devices and browser versions. It’s been available across browsers since ⁨2015年7月⁩.

StringtoString() 方法返回该字符串的值。

尝试一下

const stringObj = new String("foo");console.log(stringObj);// Expected output: String { "foo" }console.log(stringObj.toString());// Expected output: "foo"

语法

js
toString()

返回值

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

描述

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

toString() 方法要求其this 值为String 原始值或封装对象。对于其他this 值,它会抛出TypeError 而不尝试将其转换为字符串值。

由于String 没有[Symbol.toPrimitive]() 方法,当一个String对象在期望字符串的上下文中使用时(比如在模板字面量中),JavaScript 会自动调用toString() 方法。然而,String原始值不会使用toString() 方法来进行字符串强制转换——因为它们已经是字符串,所以不会进行转换。

js
String.prototype.toString = () => "已经被重写了";console.log(`${"foo"}`); // "foo"console.log(`${new String("foo")}`); // "已经被重写了"

示例

使用 toString()

以下示例输出一个String 对象的字符串值:

js
const x = new String("Hello world");console.log(x.toString()); // "Hello world"

规范

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

浏览器兼容性

参见

Help improve MDN

Learn how to contribute

This page was last modified on byMDN contributors.


[8]ページ先頭

©2009-2025 Movatter.jp