Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[zh-cn]: Update translation of String.toString() #15171

Merged
merged 1 commit into from
Aug 17, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ slug: Web/JavaScript/Reference/Global_Objects/String/toString

{{JSRef}}

字符串对象的 **`toString()`** 方法返回一个字符串,表示指定的字符串
{{jsxref("String")}} 的 **`toString()`** 方法返回该字符串的值

{{EmbedInteractiveExample("pages/js/string-tostring.html")}}

Expand All @@ -17,11 +17,21 @@ toString()

### 返回值

`String` 包装对象的字符串值
表示指定字符串值的字符串

## 描述

{{jsxref("String")}} 对象覆盖了 {{jsxref("Object")}} 对象的 `toString()` 方法;并没有继承 {{jsxref("Object.prototype.toString()")}}。对于 {{jsxref("String")}} 对象,`toString()` 方法返回一个字符串来表示这个对象,和 {{jsxref("String.prototype.valueOf()")}} 方法的返回值相同。
{{jsxref("String")}} 对象重写了 {{jsxref("Object")}} 的 `toString` 方法;它不会继承 {{jsxref("Object.prototype.toString()")}}。对于 `String` 值,`toString` 方法返回字符串本身(如果它是原始值)或 `String` 对象封装的字符串。它的实现与 {{jsxref("String.prototype.valueOf()")}} 完全相同。

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

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

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

## 示例

Expand All @@ -32,7 +42,7 @@ toString()
```js
const x = new String("Hello world");

console.log(x.toString()); // 输出 'Hello world'
console.log(x.toString()); // "Hello world"
```

## 规范
Expand Down