Object Oriented Programming in JavaScript

In the past few lessons, we went over all of the concepts you need to know about object-oriented programming.

We first started with objects and discussed the this keyword, which is used to reference the current instance of the object.

javascript
1let user = {
2  firstName: "John",
3  lastName: "Doe",
4  printUserName: function () {
5    console.log(`${this.firstName} ${this.lastName}`);
6  },
7};
8
9user.printUserName();
text
1John Doe

We then explained that this can be used outside of an object, which allows us to write constructor functions. Constructor functions are used to create objects programmatically.

javascript
1function User(name) {
2  this.name = name;
3  this.role = "Visitor";
4}
5
6let john = new User("John");
7
8console.log(john);
text
1User { name: 'John', role: 'Visitor' }

We also discussed the inheritance system for objects called prototypes.

javascript
1let user = {
2  name: "John Doe",
3
4  example() {
5    console.log(
6      "This method belongs to user, but can be inherited by the admin."
7    );
8  },
9};
10
11let admin = {
12  role: "Admin",
13};
14
15Object.setPrototypeOf(admin, user);
16
17admin.example();
text
1This method belongs to user, but can be inherited by the admin.

Wait, there is more!

You need an account to access the rest of this lesson. Our course is 50% off for limited time only! Don't miss the opportunity!

🎉 Create an Account 🎉