-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathget-and-set-prototype.js
More file actions
81 lines (64 loc) · 1.85 KB
/
get-and-set-prototype.js
File metadata and controls
81 lines (64 loc) · 1.85 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
const person = {
isHuman: true,
};
{
// using __proto__ ( NOT RECOMMENDED, deprecated)
const child = {
isStudying: true,
__proto__: person,
};
console.log(child.isStudying); // true
console.log(child.isHuman); // true
}
{
// using Object.create and direct assignments
const child = Object.create(person);
child.isStudying = true;
console.log(child.isStudying); // true
console.log(child.isHuman); // true
}
{
// using Object.assign and Object.create together
const child = Object.assign(Object.create(person), {
isStudying: true,
});
console.log(child.isStudying); // true
console.log(child.isHuman); // true
}
{
// using Object.create configurable values
const child = Object.create(person, {
// each key needs to be given configurations
isStudying: {
value: true, // the value for the key
writable: true, // whether writable key-value pair or not,
enumerable: true, //whether this key shows up while enumerating,
configurable: true, // whether this object with value,writable, enumerable, configurable is configurable
},
});
console.log(child.isStudying); // true
console.log(child.isHuman); // true
}
{
// using Object.setPrototypeOf , NOT RECOMMENDED, slow api. prototypes are not meant to be changed after object creation
const child = {
isStudying: true,
};
Object.setPrototypeOf(child, person);
console.log(child.isStudying); // true
console.log(child.isHuman); // true
}
// GETTING Prototype with Object.getPrototypeOf // Recommended way
{
const child = Object.assign(Object.create(person), {
isStudying: true,
});
console.log(Object.getPrototypeOf(child) === person);
}
// GETTING Prototype with __proto // Not Recommended
{
const child = Object.assign(Object.create(person), {
isStudying: true,
});
console.log(child.__proto__ === person);
}