Boolean.prototype.toString()

Boolean 值的 toString() 方法返回表示指定布尔值的字符串。

¥The toString() method of Boolean values returns a string representing the specified boolean value.

Try it

语法

¥Syntax

js
toString()

参数

¥Parameters

没有任何。

¥None.

返回值

¥Return value

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

¥A string representing the specified boolean value.

描述

¥Description

Boolean 对象重写了 ObjecttoString 方法;它不继承 Object.prototype.toString()。对于 Boolean 值,toString 方法返回布尔值的字符串表示形式,即 "true""false"

¥The Boolean object overrides the toString method of Object; it does not inherit Object.prototype.toString(). For Boolean values, the toString method returns a string representation of the boolean value, which is either "true" or "false".

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

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

由于 Boolean 没有 [Symbol.toPrimitive]() 方法,因此当在需要字符串的上下文中(例如在 模板文字 中)使用 Boolean 对象时,JavaScript 会自动调用 toString() 方法。然而,布尔原始值不会参考 toString() 方法来转换为 强制为字符串 — 相反,它们会使用与初始 toString() 实现相同的算法直接转换。

¥Because Boolean doesn't have a [Symbol.toPrimitive]() method, JavaScript calls the toString() method automatically when a Boolean object is used in a context expecting a string, such as in a template literal. However, boolean primitive values do not consult the toString() method to be coerced to strings — rather, they are directly converted using the same algorithm as the initial toString() implementation.

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

示例

¥Examples

使用 toString()

¥Using toString()

js
const flag = new Boolean(true);
console.log(flag.toString()); // "true"
console.log(false.toString()); // "false"

规范

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

¥Specifications

浏览器兼容性

BCD tables only load in the browser

¥Browser compatibility

也可以看看