The class notation allows you to create an inheritance system as well. You can extend a class to another class using the extends
keyword. For example, here is a User
class:
javascript
1class User {
2 constructor(name) {
3 this.name = name;
4
5 this.firstName;
6 this.lastName;
7 }
8
9 get name() {
10 return `${this.firstName} ${this.lastName}`;
11 }
12
13 set name(name) {
14 [this.firstName, this.lastName] = name.split(" ");
15 }
16}
17
18let user = new User("John Doe");
19
20console.log(user);
text
1User { firstName: 'John', lastName: 'Doe' }
And then, you might need a Profile
class that extends to User
:
javascript
1class Profile extends User {
2 create() {
3 console.log("Profile created.");
4 }
5}
6
7let profile = new Profile("John Doe");
8
9console.log(Object.getPrototypeOf(profile));
text
1User {}
As you can see, the prototype of profile
is set to be User
. You can access the create()
method from profile
, but not user
:
javascript
1profile.create(); // -> Profile created.
2user.create(); // -> Error
text
1Profile created.
2/Users/. . ./index.js:29
3user.create();
4 ^
5
6TypeError: user.created is not a function
7 at Object.<anonymous> (/Users/. . ./index.js:29:6)
8 . . .
9
10Node.js v21.6.0
Technically, you don't need to know how this works internally, but if you are interested, when you use extends
to create a class, a prototype
property will be set to that class.