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

Symbol.toPrimitive 属性的属性特性:
writable false
enumerable false
configurable false

描述

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

示例

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

// 没有 Symbol.toPrimitive 属性的对象
var obj1 = {};
console.log(+obj1);     // NaN
console.log(`${obj1}`); // "[object Object]"
console.log(obj1 + ""); // "[object Object]"

// 拥有 Symbol.toPrimitive 属性的对象
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"

规范

规范 状态 注释
ECMAScript 2015 (6th Edition, ECMA-262)
Symbol.toPrimitive
Standard 原始定义
ECMAScript Latest Draft (ECMA-262)
Symbol.toPrimitive
Draft  

浏览器兼容性

We're converting our compatibility data into a machine-readable JSON format. This compatibility table still uses the old format, because we haven't yet converted the data it contains. Find out how you can help!

Feature Chrome Firefox (Gecko) Internet Explorer Opera Safari
Basic support 48 44 (44) ? ? ?
Feature Android Chrome for Android Firefox Mobile (Gecko) IE Mobile Opera Mobile Safari Mobile
Basic support ? ? 44.0 (44) ? ? ?

其他资料