In practice, we often encounter situations where we need to take an existing object, and then extend it to create slightly different variants.
For example, you could have a user
object.
1let user = {
2 firstName: "John",
3 lastName: "Doe",
4
5 get fullName() {
6 return `${this.firstName} ${this.lastName}`;
7 },
8
9 set fullName(value) {
10 [this.firstName, this.lastName] = value.split(" ");
11 },
12};
And then based on user
, you could have admin
, editor
, and visitor
, which are variants of user
.
1let admin = {
2 firstName: "John",
3 lastName: "Doe",
4 role: "Admin",
5
6 get fullName() {
7 return `${this.firstName} ${this.lastName}`;
8 },
9
10 set fullName(value) {
11 [this.firstName, this.lastName] = value.split(" ");
12 },
13};
14
15let editor = {
16 firstName: "John",
17 lastName: "Doe",
18 role: "Editor",
19
20 . . .
21};
22
23let visitor = {
24 firstName: "John",
25 lastName: "Doe",
26 role: "Visitor",
27
28 . . .
29};
30
In this example, we hardcoded everything. But notice that there are many repetitions. And when you need to change the properties in the user
object, you'll have to change the other objects in the exact same way. That is a lot more space for potential mistakes.
A better way to do this is to make admin
, editor
, and visitor
extend on user
.
Object.setPrototypeOf
Instead of creating the admin
object directly, you should use the Object.setPrototypeOf()
method, which is a built-in method used to extend an object based on a prototype. In this case, the prototype would be user
.
1let user = {
2 firstName: "John",
3 lastName: "Doe",
4
5 get fullName() {
6 return `${this.firstName} ${this.lastName}`;
7 },
8
9 set fullName(value) {
10 [this.firstName, this.lastName] = value.split(" ");
11 },
12};
13
14let admin = {
15 role: "Admin",
16};
17
18Object.setPrototypeOf(admin, user);