-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathObject-toPrimitives.js
More file actions
105 lines (73 loc) · 2.22 KB
/
Object-toPrimitives.js
File metadata and controls
105 lines (73 loc) · 2.22 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
//: OBJECT TO PRIMITIVES
//* Conversion Rules
/* => There's no conversion to boolean. All object are true in a boolean context, as simple as that,
=> The numeric conversion happens when we subtract or apply mathmatical function. For instance Data object can be subtracted, and the result of dat1- date2.
=> As for the string conversion - it usually happens when we output an object with alert(obj) and in similar contexts*/
//* Hints
/* There are three variants of type conversion, that happen in various situations. They're called "hints" */
// "string" =>
alert(obj);
// using object as a property key
anotherObj[obj] = 123;
// "number" =>
// explicit conversion
let num = Number(obj);
// maths (except binary plus)
let n = +obj; // unary plus
let delta = date1 - date2;
// less/greater comparison
let greater = user1 > user2;
// "Default"
/* Occurs in rare cases when the operators is "not sure" what type to expect */
// binary plus uses the "default" hint
let total = obj1 + obj2;
// obj == number uses the "default" hint
if (user == 1) {
}
//* Symbol.toPrimitive
/* There's a built-in symbol named Symbol.toPrimitive that should be used to name the conversion method, */
let user = {
name: "Jhon",
money: 1000,
[Symbol.toPrimitive](hint) {
console.log(`hint: ${hint}`);
return hint == "string" ? `{name: "${this.name}}` : this.money;
},
};
console.log(user);
console.log(+user);
console.log(user + 500);
//* toString/valueOf
let person = { name: "Jhon" };
console.log(user); // [object Object]
console.log(person.valueOf() === user); // => true
let car = {
name: "TATA XP",
money: 100000,
// for hint="string"
toString() {
return `name: ${this.name}`;
},
// for hint="number" or "default"
valueOf() {
return this.money;
},
};
console.log(car); // => {name: "TATA Xp"}
console.log(+car); // => 1000
console.log(car + 1000); // => 1500
//* Further conversions
let obj = {
// toString handles all conversion in the absence of other methods
toString() {
return "10";
},
};
console.log(obj * 10); // 100
let obj2 = {
toString() {
return "2";
},
};
//? Binary plus operator concatenat a value
alert(obj2 + 2); // 22 ("2" + 2), conversion to primitive returned a string => concatenation