In ECMAScript 6, a new Symbol.toPrimitive
symbol is introduced, which, when used as an object key, should define a function to return the primitive value of an object:
let object = { aNumber: 0, [Symbol.toPrimitive]() { return this.aNumber; } }; object.aNumber = 5; console.log(object + 2) // 7
However, there is also the Object.prototype.valueOf
function, which, according to the documentation, could be redefined to convert an object to the primitive value:
let object = { aNumber: 0, valueOf() { return this.aNumber; } }; object.aNumber = 5; console.log(object + 2) // 7
So, which of these ways to convert an object to its primitive value should be used in ES6 when defining a new object?
toPrimitive is a symbol that specifies a function valued property that is called to convert an object to a corresponding primitive value.
The valueOf() method returns the primitive value of a string. The valueOf() method does not change the original string. The valueOf() method can be used to convert a string object into a string.
The valueOf() method returns the primitive value of the specified object.
Symbols are often used to add unique property keys to an object that won't collide with keys any other code might add to the object, and which are hidden from any mechanisms other code will typically use to access the object. That enables a form of weak encapsulation, or a weak form of information hiding.
The main purpose of Symbol.toPrimitive
is to change the order in which toString
and valueOf
are called in different coercion scenarios.
An example of this is the Date
native object, where it will convert the value to a string instead of a number by default:
console.log(1 + new Date()); // "1Mon Aug 15 2016 13:25:31 GMT-0500 (EST)" var a = new Date(1000); console.log(a == 1000); // false console.log(a == a.toString()); // true
If you do not intend to do this, you should just override both obj.valueOf
and obj.toString
to match the behaviour that you want -- this is what most of the native objects do in JavaScript.
Note that both valueOf
and toString
should be overridden, as the ToPrimitive abstract operation may call either of them for coercion depending on the reason ToPrimitive is being called.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With