在线文档教程

Symbol.toPrimitive

Symbol.toPrimitive

Symbol.toPrimitive 指将被调用的指定函数值的属性转换为相对应的原始值。

| Symbol.toPrimitive 属性的属性特性: |

|:----|

| Writable | no |

| Enumerable | no |

| Configurable | no |

描述

在 Symbol.toPrimitive属性(用作函数值)的帮助下,一个对象可被转换为原始值。该函数由字符串参数 hint 调用,目的是指定原始值转换结果的首选类型。 hint 参数可以是"number"、"string" 和 "default" 中的一种。

示例

下列的例子展示了 Symbol.toPrimitive属性如何将对象转换为原始值。

// An object without Symbol.toPrimitive property. var obj1 = {}; console.log(+obj1 // NaN console.log(`${obj1}` // "[object Object]" console.log(obj1 + '' // "[object Object]" // An object with Symbol.toPrimitive property. var obj2 = { [Symbol.toPrimitive](hint) { if (hint == 'number') { return 10; } if (hint == 'string') { return 'hello'; } return true; } }; console.log(+obj2 // 10 -- hint is "number" console.log(`${obj2}` // "hello" -- hint is "string" console.log(obj2 + '' // "true" -- hint is "default"

规范

SpecificationStatusComment
ECMAScript 2015 (6th Edition, ECMA-262)The definition of 'Symbol.toPrimitive' in that specification.StandardInitial definition.
ECMAScript Latest Draft (ECMA-262)The definition of 'Symbol.toPrimitive' in that specification.Draft

浏览器兼容性

FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support48(Yes)44 (44)???

FeatureAndroidChrome for AndroidEdgeFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support??(Yes)44.0 (44)???