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 |
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. |
| Desktop | Mobile | Server | |||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
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 |
完整支持
不支持
Date.prototype[@@toPrimitive]
Symbol.prototype[@@toPrimitive]
Object.prototype.toString()
Object.prototype.valueOf()
Symbol
Function
Object
Object.prototype.__defineGetter__()
Object.prototype.__defineSetter__()
Object.prototype.__lookupGetter__()
Object.prototype.__lookupSetter__()
Object.prototype.hasOwnProperty()
Object.prototype.isPrototypeOf()
Object.prototype.propertyIsEnumerable()
Object.prototype.toLocaleString()
Object.prototype.toSource()
Object.prototype.toString()
Object.prototype.valueOf()
Object.setPrototypeOf()