[@@toPrimitive]() 方法可以转换一个 Date 对象到一个原始值。
用法
Date()[Symbol.toPrimitive](hint);
返回值
给出的 Date 的原始值。根据传入参数的不同,可以返回 string 或 number 类型。
说明
Date 对象的 [@@toPrimitive]() 方法可以返回一个原始值,或是 string,或是number。
如果 hint 是 "string" 或 "default",[@@toPrimitive]() 将会调用 TypeError。
如果 hint 是 "number",[@@toPrimitive]() 会首先尝试 valueOf,若失败再尝试 toString。
当期望一个原始值却收到一个对象时,JavaScript 可以自动的调用 [@@toPrimitive]() 方法来将一个对象转化成原始值,所以你很少会需要自己调用这个方法。
Specifications
| Specification | Status | Comment |
|---|---|---|
| ECMAScript 2015 (6th Edition, ECMA-262) Date.prototype.@@toPrimitive |
Standard | Initial definition. |
| ECMAScript Latest Draft (ECMA-262) Date.prototype.@@toPrimitive |
Draft |
Browser compatibility
The compatibility table in this page is generated from structured data. If you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request.
Update compatibility data on GitHub
| Desktop | Mobile | Server | |||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
@@toPrimitive |
Chrome Full support 47 | Edge Full support 15 | Firefox Full support 44 | IE No support No | Opera Full support 34 | Safari ? | WebView Android Full support 47 | Chrome Android Full support 47 | Firefox Android Full support 44 | Opera Android Full support 34 | Safari iOS ? | Samsung Internet Android Full support 5.0 | nodejs Full support 6.0.0 |
Legend
- Full support
- Full support
- No support
- No support
- Compatibility unknown
- Compatibility unknown