In javascript, there is a symbolic property known as Symbol.toprimitive, which have function value, am I right?
If so, then in this method, the first word (ie. Symbol) is an system symbol?
And when we call this method, is there a formation of temporary object as we are creating property for a value that is primitive (symbol), of which value is an method?
And third confusion is in this method (ie. [Symbol.toprimitive] (hint), how the parameter hint knowns that hint should be "string" or "number" or "default" , I mean I know the rules but from where this parameter gets its value?
Thanks for your valuable answer :)
CodePudding user response:
...there is a symbolic property known as Symbol.toprimitive, which have function value, am I right?
No, Symbol.toPrimitive is a Symbol, not a function. It's used as the key of an object property whose value should be a function, but it's a Symbol.
...then in this method, the first word (ie. Symbol) is an system symbol?
It's the Symbol global object, which is a container for "well-known symbols" used for various purposes in JavaScript code.
And when we call this method, is there a formation of temporary object as we are creating property for a value that is primitive (symbol), of which value is an method?
Symbol.toPrimitive is not a method, so the question doesn't come up.
And third confusion is in this method (ie. [Symbol.toprimitive] (hint), how the parameter hint knowns that hint should be "string" or "number" or "default" , I mean I know the rules but from where this parameter gets its value?
The value of the hint is built into the places in the JavaScript specification that call the function. For example, the unary - operator uses ToNumeric on its operand, which uses ToPrimitive, passing in the fact that it wants a number. ToPrimitive is what passes the "number" hint to the [Symbol.toPrimitive] (aka @@toPrimitive) method of the object.
Let's consider a simple example, which should help you understand things a bit more:
// An object with its own Symbol.toPrimitive property
// referring to a function that implements the behavior
// we want for this object
const obj = {
[Symbol.toPrimitive](hint) {
console.log(`The hint is ${hint}`);
return hint === "number" ? 42 : "forty-two";
}
};
// `-` uses ToNumeric which uses ToPrimitive asking for a
// number if possible
let x = 4 - obj;
console.log(`x = ${x}`);
// In contrast, string concatenation doesn't have a preference
let y = "" obj;
console.log(`y = ${y}`);
// But the String function, which always wants to get a
// string if it can, asks for a string
let z = String(obj);
console.log(`z = ${z}`);
