Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Symbol.toPrimitive vs Object.prototype.valueOf

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?

like image 420
Ivan Akulov Avatar asked Jan 01 '15 11:01

Ivan Akulov


People also ask

What is symbol toPrimitive?

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

What is valueOf() in JavaScript?

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.

What does this valueOf () return in Javascript?

The valueOf() method returns the primitive value of the specified object.

What is the use of symbols in Javascript?

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.


1 Answers

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.

like image 164
Qantas 94 Heavy Avatar answered Sep 21 '22 21:09

Qantas 94 Heavy