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"
规范
Specification | Status | Comment |
---|---|---|
ECMAScript 2015 (6th Edition, ECMA-262)The definition of 'Symbol.toPrimitive' in that specification. | Standard | Initial definition. |
ECMAScript Latest Draft (ECMA-262)The definition of 'Symbol.toPrimitive' in that specification. | Draft | |
浏览器兼容性
Feature | Chrome | Edge | Firefox (Gecko) | Internet Explorer | Opera | Safari |
---|---|---|---|---|---|---|
Basic support | 48 | (Yes) | 44 (44) | ? | ? | ? |
Feature | Android | Chrome for Android | Edge | Firefox Mobile (Gecko) | IE Mobile | Opera Mobile | Safari Mobile |
---|---|---|---|---|---|---|---|
Basic support | ? | ? | (Yes) | 44.0 (44) | ? | ? | ? |