Date.prototype[Symbol.toPrimitive]()
Date
实例的 [Symbol.toPrimitive]()
方法返回表示该日期的原始值。它可以是字符串或数字,具体取决于给出的提示。
¥The [Symbol.toPrimitive]()
method of Date
instances returns a primitive value representing this date. It may either be a string or a number, depending on the hint given.
Try it
语法
参数
返回值
¥Return value
如果 hint
是 "string"
或 "default"
,则此方法返回 将 this
值强制转换为字符串 的字符串(首先尝试 toString()
,然后尝试 valueOf()
)。
¥If hint
is "string"
or "default"
, this method returns a string by coercing the this
value to a string (first trying toString()
then trying valueOf()
).
如果 hint
是 "number"
,则此方法返回 将 this
值强制转换为数字 之前的数字(首先尝试 valueOf()
,然后尝试 toString()
)。
¥If hint
is "number"
, this method returns a number by coercing the this
value to a number (first trying valueOf()
then trying toString()
).
例外情况
描述
¥Description
[Symbol.toPrimitive]()
方法是 类型强制协议 的一部分。JavaScript 总是优先调用 [Symbol.toPrimitive]()
方法来将对象转换为原始值。你很少需要自己调用 [Symbol.toPrimitive]()
方法;当遇到需要原始值的对象时,JavaScript 会自动调用它。
¥The [Symbol.toPrimitive]()
method is part of the type coercion protocol. JavaScript always calls the [Symbol.toPrimitive]()
method in priority to convert an object to a primitive value. You rarely need to invoke the [Symbol.toPrimitive]()
method yourself; JavaScript automatically invokes it when encountering an object where a primitive value is expected.
Date
对象的 [Symbol.toPrimitive]()
方法通过调用 this.valueOf()
并返回数字或调用 this.toString()
并返回字符串来返回原始值。它的存在是为了覆盖默认的 原始强制 进程以返回字符串而不是数字,因为默认情况下,原始强制转换会在 toString()
之前调用 valueOf()
。使用自定义 [Symbol.toPrimitive]()
,new Date(0) + 1
返回 "Thu Jan 01 1970 00:00:00 GMT+0000 (Coordinated Universal Time)1"
(字符串)而不是 1
(数字)。
¥The [Symbol.toPrimitive]()
method of the Date
object returns a primitive value by either invoking this.valueOf()
and returning a number, or invoking this.toString()
and returning a string. It exists to override the default primitive coercion process to return a string instead of a number, because primitive coercion, by default, calls valueOf()
before toString()
. With the custom [Symbol.toPrimitive]()
, new Date(0) + 1
returns "Thu Jan 01 1970 00:00:00 GMT+0000 (Coordinated Universal Time)1"
(a string) instead of 1
(a number).
示例
使用 Symbol.toPrimitive
¥Using [Symbol.toPrimitive]()
const d = new Date(0); // 1970-01-01T00:00:00.000Z
d[Symbol.toPrimitive]("string"); // "Thu Jan 01 1970 00:00:00 GMT+0000 (Coordinated Universal Time)"
d[Symbol.toPrimitive]("number"); // 0
d[Symbol.toPrimitive]("default"); // "Thu Jan 01 1970 00:00:00 GMT+0000 (Coordinated Universal Time)"
规范
Specification |
---|
ECMAScript Language Specification # sec-date.prototype-@@toprimitive |
浏览器兼容性
BCD tables only load in the browser
也可以看看
¥See also