OOJS - Object Oriented JavaScript - Part 4

OOJS - Object Oriented JavaScript - Part 4

ยท

5 min read

In this part you'll understand about Class, Constructor, this keyword and how to create multiple instances of objects with the help of a Class's constructor.

Hi! I am Sunil! I am a front-end developer and this is the fourth part of 'OOJS - Object Oriented JavaScript' series. You can find the other parts of this series here. For more useful content and articles, follow me.

This series will make you understand -

  • Creating your own objects using object literal notation.
  • Encapsulation, instances.
  • JavaScript Classes and Constructors.
  • Inheritance.
  • Method Chaining.
  • Prototypes and Prototype inheritance.

OOJS - Object Oriented JavaScript - Part 4

In third part of this blog series we understood how we can update properties of an object and ways to access its properties and values. In this blog we'll understand how to create multiple instances of objects with the help of a Class's constructor. Lets get started.

We had this piece of code left in our last blog-

var userOne = {
    email: 'sunilnet4@gmail.com',
    name : 'Sunil',
    friends: 'Rekha',
    login: function(){
        console.log(this.email, 'has logged in');
    },
    logout(){
        console.log(this.email, 'has logged out');
    }
};

This code above is enough to create a user with certain properties and methods. But what if we have to create hundreds and thousands of users like employees of an organization or students in a college.

One thing we can do is replicate the above code with different properties, but that would be a lot of code repetition and nobody would want to be in that scenario.

To solve the purpose, there is a couple of ways. One way is to use the prototype model. But with the release of ES6 we got a little syntactic sugar so that we can solve this problem using classes as well. Under the hood, classes essentially do the same thing as prototypes in JavaScript. Now some devs find it easier to work with these classes and some don't as JavaScript as a language doesn't have classes built into it. So this ES6 is just some syntactic sugar which emulates the idea of classes but under the hood its just same as working with JavaScript prototype model (which we'll surely cover by the end of this series).

Coming back to Classes, we define a class in the following way-

class User {
    constructor(){

    }
};

Notice that, we have a class keyword followed by an uppercased class of name User and an immediate code block. There is no = sign between name and code block unlike in object declaration. Keep this syntax in mind while working with Classes.

A class also hosts a constructor function which serves the purpose of making new object instances.

So, instead of replicating the object multiple times what we can do is get rid of all the previous code and-

Step 1- Create a class.

Step 2- Create an object instance of the class.

Now, log the object instance in the console, just like below-

class User {
    constructor(){
        this.email = "sunilnet4@gmail.com";
        this.name = "Sunil";
        this.friends = "Rekha";
    }
};

let userOne = new User();

console.log(userOne);

oojs4 -1.png

We can see in the console, an object instance of the User class.

Here, the new keyword is-

  1. creating a new empty object { }
  2. sets the value of this to be the new empty object. Meaning, this refers to the empty object.
  3. calls the constructor method.

But there is a catch here. All our values are hard coded, which means we can not differentiate between two or more instances because the values will always remain the same.

So in this case, we can make use of this keyword and take value as arguments.

class User {
    constructor(email, name, friends){
        this.email = email ;
        this.name = name;
        this.friends = friends;
    }
};

let userOne = new User("sunilnet4@gmail.com", "Sunil", "Rekha");

console.log(userOne);

oojs4 -2.png

We can see the object in the console which, this time, is created dynamically. Similarly, we can create multiple object instances of User class-

let userTwo = new User("dan@gmail.com", "Dan", "Ambrov");
let userThree = new User("jack@gmail.com", "Jack", "Daniel");

console.log(userTwo);
console.log(userThree);

Untill now we saw properties defined in the constructor function of the class, and we conveniently omitted the methods. Thats because methods aren't defined in constructor rather, they are defined outside the constructor function, in the class itself.

class User {
    constructor(email, name, friends){
        this.email = email ;
        this.name = name;
        this.friends = friends;
    }

    login(){
        console.log(this.email, "is logged in");
    }

    logout(){
        console.log(this.email, "is logged out");
    }
};

let userOne = new User("sunilnet4@gmail.com", "Sunil", "Rekha");
let userTwo = new User("dan@gmail.com", "Dan", "Ambrov");

console.log(userOne.login());
console.log(userTwo.logout());

You can see that we have two object instances of the User class here, userOne and userTwo with the value of its properties passed as arguments. The methods however are in the class itself and the this in the methods refer to object instance which is created. So, no matter what the object name is, this.email will pick up the email property of that object.

oojs4 -3.png

From this, we can conclude that we can use the ES6 classes to create object instances of a class which is highly readable and maintainable.

In the next blog we'll understand about a little trick called Method Chaining. Stay tuned and follow me ๐Ÿ‘‡


You can reach me here.

๐Ÿ‘‰ If you like this blog you can tweet about it.

๐Ÿ‘‰ Also, connect with me on Linkedin to be the part of 15000+ members strong family of devs and tech recruiters.

๐Ÿ‘‰ As an appreciation, you can follow me on Github and star my repos if you find them useful.

๐Ÿ‘‰ You can also subscribe to my youtube channel. I'll regularly post useful and some unique code and productivity targetting stuff here.

Lets get things working, see you again. ๐Ÿค˜

ย