WellKnownSymbols (WN09)
1: const myObj = {
2: name: "User1",
3: [Symbol.toPrimitive](hint) { // Customize type coercion behavior
4: if (hint === "string") {
5: return `String:${this.name}`; // Convert to string when string context is required
6: } else if (hint === 'number') {
7: return 10; // For example, or use different logic
8: } else {
9: return this.name; //default behavior if not converted to string or number
10: }
11: }
12: };
13:
14: console.log(String(myObj)); // Output: String:User1
15: console.log(10 + myObj); //10User1, because myObj won't be converted into number, because no explicit Number(myObj) is used, only 10 + myObj
16: console.log(Number(myObj)); // 10
Symbol.toPrimitive allows you to customize how an object is converted to a primitive value (string, number, or default) String:User1 10User1 10
WellKnownSymbols context:
ES6 context:
Comments (
)
)
Link to this page:
http://www.vb-net.com/JavascriptES6/WN09.htm
|
|