In the following code :
JavaScript
x
26
26
1
let user = {
2
name: "John",
3
surname: "Smith",
4
5
set fullName(value) {
6
[this.name, this.surname] = value.split(" ");
7
},
8
9
get fullName() {
10
return `${this.name} ${this.surname}`;
11
}
12
};
13
14
let admin = {
15
__proto__: user,
16
isAdmin: true
17
};
18
19
alert(admin.fullName); // John Smith (*)
20
21
// setter triggers!
22
admin.fullName = "Alice Cooper"; // (**)
23
24
alert(admin.fullName); // Alice Cooper, state of admin modified
25
alert(user.fullName); // John Smith, state of user protected
26
The user Object is the prototype of admin Object, As we see line (**) sets the fullName for admin Object, although user Object remains the way it was.
So is it correct to say that user Properties & Methods are copied to admin Object ?
Advertisement
Answer
Using Object.getOwnPropertyNames
reveals that by using admin.fullName = "Alice Cooper"
you actually create new properties instead of overriding anything.
JavaScript
1
23
23
1
let user = {
2
name: "John",
3
surname: "Smith",
4
5
set fullName(value) {
6
[this.name, this.surname] = value.split(" ");
7
},
8
9
get fullName() {
10
return `${this.name} ${this.surname}`;
11
}
12
};
13
14
let admin = {
15
__proto__: user,
16
isAdmin: true
17
};
18
19
console.log(Object.getOwnPropertyNames(admin));
20
admin.fullName = "Alice Cooper";
21
22
console.log(Object.getOwnPropertyNames(admin));
23
console.log(Object.getOwnPropertyNames(user));
Changing the the properties of the prototype reveals that it’s references
JavaScript
1
23
23
1
let user = {
2
name: "John",
3
surname: "Smith",
4
5
set fullName(value) {
6
[this.name, this.surname] = value.split(" ");
7
},
8
9
get fullName() {
10
return `${this.name} ${this.surname}`;
11
}
12
};
13
14
let admin = {
15
__proto__: user,
16
isAdmin: true
17
};
18
19
console.log(admin);
20
user.fullName = "Alice Cooper";
21
22
console.log(admin);
23
console.log(user);