Object.prototype.toString()

Object 实例的 toString() 方法返回表示该对象的字符串。此方法旨在由自定义 类型强制 逻辑的派生对象覆盖。

¥The toString() method of Object instances returns a string representing this object. This method is meant to be overridden by derived objects for custom type coercion logic.

Try it

语法

¥Syntax

js
toString()

参数

¥Parameters

默认情况下,toString() 不带任何参数。然而,从 Object 继承的对象可能会用它们自己的带有参数的实现来覆盖它。例如,Number.prototype.toString()BigInt.prototype.toString() 方法采用可选的 radix 参数。

¥By default toString() takes no parameters. However, objects that inherit from Object may override it with their own implementations that do take parameters. For example, the Number.prototype.toString() and BigInt.prototype.toString() methods take an optional radix parameter.

返回值

¥Return value

代表对象的字符串。

¥A string representing the object.

描述

¥Description

JavaScript 将 toString 方法调用到 将对象转换为原始值。你很少需要自己调用 toString 方法;当遇到需要原始值的对象时,JavaScript 会自动调用它。

¥JavaScript calls the toString method to convert an object to a primitive value. You rarely need to invoke the toString method yourself; JavaScript automatically invokes it when encountering an object where a primitive value is expected.

该方法由 字符串转换 优先调用,但 数值转换原始转换 优先调用 valueOf()。但是,由于基类 valueOf() 方法返回一个对象,因此通常最后会调用 toString() 方法,除非该对象覆盖 valueOf()。例如,+[1] 返回 1,因为它的 toString() 方法返回 "1",然后将其转换为数字。

¥This method is called in priority by string conversion, but numeric conversion and primitive conversion call valueOf() in priority. However, because the base valueOf() method returns an object, the toString() method is usually called in the end, unless the object overrides valueOf(). For example, +[1] returns 1, because its toString() method returns "1", which is then converted to a number.

所有从 Object.prototype 继承的对象(即除 null-原型对象 之外的所有对象)都继承 toString() 方法。当你创建自定义对象时,你可以重写 toString() 来调用自定义方法,以便你的自定义对象可以转换为字符串值。或者,你可以添加 [Symbol.toPrimitive]() 方法,该方法允许对转换过程进行更多控制,并且对于任何类型转换始终优先于 valueOftoString

¥All objects that inherit from Object.prototype (that is, all except null-prototype objects) inherit the toString() method. When you create a custom object, you can override toString() to call a custom method, so that your custom object can be converted to a string value. Alternatively, you can add a [Symbol.toPrimitive]() method, which allows even more control over the conversion process, and will always be preferred over valueOf or toString for any type conversion.

要将基础 Object.prototype.toString() 与覆盖它的对象一起使用(或在 nullundefined 上调用它),你需要对其调用 Function.prototype.call()Function.prototype.apply(),并将要检查的对象作为第一个参数传递(称为 thisArg)。

¥To use the base Object.prototype.toString() with an object that has it overridden (or to invoke it on null or undefined), you need to call Function.prototype.call() or Function.prototype.apply() on it, passing the object you want to inspect as the first parameter (called thisArg).

js
const arr = [1, 2, 3];

arr.toString(); // "1,2,3"
Object.prototype.toString.call(arr); // "[object Array]"

Object.prototype.toString() 返回 "[object Type]",其中 Type 是对象类型。如果对象具有值为字符串的 Symbol.toStringTag 属性,则该值将用作 Type。许多内置对象(包括 MapSymbol)都有 Symbol.toStringTag。ES6 之前的一些对象没有 Symbol.toStringTag,但仍然有一个特殊的标签。它们包括(标签与下面给出的类型名称相同):

¥Object.prototype.toString() returns "[object Type]", where Type is the object type. If the object has a Symbol.toStringTag property whose value is a string, that value will be used as the Type. Many built-in objects, including Map and Symbol, have a Symbol.toStringTag. Some objects predating ES6 do not have Symbol.toStringTag, but have a special tag nonetheless. They include (the tag is the same as the type name given below):

arguments 对象返回 "[object Arguments]"。其他所有内容(包括用户定义的类),除非使用自定义 Symbol.toStringTag,都将返回 "[object Object]"

¥The arguments object returns "[object Arguments]". Everything else, including user-defined classes, unless with a custom Symbol.toStringTag, will return "[object Object]".

nullundefined 上调用 Object.prototype.toString() 分别返回 [object Null][object Undefined]

¥Object.prototype.toString() invoked on null and undefined returns [object Null] and [object Undefined], respectively.

示例

¥Examples

重写自定义对象的 toString

¥Overriding toString for custom objects

你可以创建一个要调用的函数来代替默认的 toString() 方法。你创建的 toString() 函数应返回一个字符串值。如果它返回一个对象并且在 类型转换 期间隐式调用该方法,则忽略其结果并使用相关方法 valueOf() 的值,或者如果这些方法都没有返回原语,则抛出 TypeError

¥You can create a function to be called in place of the default toString() method. The toString() function you create should return a string value. If it returns an object and the method is called implicitly during type conversion, then its result is ignored and the value of a related method, valueOf(), is used instead, or a TypeError is thrown if none of these methods return a primitive.

以下代码定义了 Dog 类。

¥The following code defines a Dog class.

js
class Dog {
  constructor(name, breed, color, sex) {
    this.name = name;
    this.breed = breed;
    this.color = color;
    this.sex = sex;
  }
}

如果你在 Dog 的实例上显式或隐式调用 toString() 方法,它将返回从 Object 继承的默认值:

¥If you call the toString() method, either explicitly or implicitly, on an instance of Dog, it returns the default value inherited from Object:

js
const theDog = new Dog("Gabby", "Lab", "chocolate", "female");

theDog.toString(); // "[object Object]"
`${theDog}`; // "[object Object]"

以下代码覆盖默认的 toString() 方法。此方法生成一个包含对象的 namebreedcolorsex 的字符串。

¥The following code overrides the default toString() method. This method generates a string containing the name, breed, color, and sex of the object.

js
class Dog {
  constructor(name, breed, color, sex) {
    this.name = name;
    this.breed = breed;
    this.color = color;
    this.sex = sex;
  }
  toString() {
    return `Dog ${this.name} is a ${this.sex} ${this.color} ${this.breed}`;
  }
}

使用前面的代码后,只要在字符串上下文中使用 Dog 的实例,JavaScript 就会自动调用 toString() 方法。

¥With the preceding code in place, any time an instance of Dog is used in a string context, JavaScript automatically calls the toString() method.

js
const theDog = new Dog("Gabby", "Lab", "chocolate", "female");

`${theDog}`; // "Dog Gabby is a female chocolate Lab"

使用 toString() 检测对象类

¥Using toString() to detect object class

toString() 可用于每个对象,并且(默认情况下)允许你获取其类。

¥toString() can be used with every object and (by default) allows you to get its class.

js
const toString = Object.prototype.toString;

toString.call(new Date()); // [object Date]
toString.call(new String()); // [object String]
// Math has its Symbol.toStringTag
toString.call(Math); // [object Math]

toString.call(undefined); // [object Undefined]
toString.call(null); // [object Null]

这样使用 toString() 是不可靠的;对象可以通过定义 Symbol.toStringTag 属性来更改 Object.prototype.toString() 的行为,从而导致意外结果。例如:

¥Using toString() in this way is unreliable; objects can change the behavior of Object.prototype.toString() by defining a Symbol.toStringTag property, leading to unexpected results. For example:

js
const myDate = new Date();
Object.prototype.toString.call(myDate); // [object Date]

myDate[Symbol.toStringTag] = "myDate";
Object.prototype.toString.call(myDate); // [object myDate]

Date.prototype[Symbol.toStringTag] = "prototype polluted";
Object.prototype.toString.call(new Date()); // [object prototype polluted]

规范

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

¥Specifications

浏览器兼容性

BCD tables only load in the browser

¥Browser compatibility

也可以看看