Symbol.toPrimitive is a symbol that specifies a function valued property that is called to convert an object to a corresponding primitive value.

The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.

描述

With the help of the Symbol.toPrimitive property (used as a function value), an object can be converted to a primitive value. The function is called with a string argument hint , which specifies the preferred type of the result primitive value. The hint argument can be one of " number " , " string " ,和 " default " .

特性属性在 Symbol.toPrimitive
可写 no
可枚举 no
可配置 no

范例

Modifying primitive values converted from an object

Following example describes how Symbol.toPrimitive property can modify the primitive value converted from an object.

// 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"
					

规范

规范
ECMAScript (ECMA-262)
The definition of 'Symbol.toPrimitive' in that specification.

浏览器兼容性

The compatibility table on 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. 更新 GitHub 上的兼容性数据
Desktop Mobile Server
Chrome Edge Firefox Internet Explorer Opera Safari Android webview Chrome for Android Firefox for Android Opera for Android Safari on iOS Samsung Internet Node.js
toPrimitive Chrome 47 Edge 15 Firefox 44 IE No Opera 34 Safari 10 WebView Android 47 Chrome Android 47 Firefox Android 44 Opera Android 34 Safari iOS 10 Samsung Internet Android 5.0 nodejs 6.0.0

图例

完整支持

完整支持

不支持

不支持

另请参阅

元数据

  • 最后修改: