DEV Community

Cover image for Getting Started with JavaScript Classes
Alok Kumar
Alok Kumar

Posted on • Updated on

Getting Started with JavaScript Classes

Hey All πŸ‘‹ , with this article I'm going to start a series of articles on JavaScript concepts. So I'm starting off this series with an article on JavaScript Classes. In this article, I'm going to cover all you need to get started with JS classes.


Table Of Contents -

  • Basics of JS Classes
  • getters and setters
  • static methods
  • inheritance and extends
  • polymorphism

Basics of JS Classes

" In object-oriented programming, a class is an extensible program-code-template for creating objects, providing initial values for state (member variables) and implementations of behavior (member functions or methods). " - Wikipedia

In simpler words, Classes are the blueprints used to create objects.

Note: JavaScript objects are entities having properties and methods.

Let's understand Classes with the help of this example -

Classes

Classes are like templates. We can see that we have one Car class having a property color in the picture, but we have not specified which color.

With the help of this class, we can create different objects with specific colors, like if we pass red as a color parameter, then a red car is created( i.e., object with red color property).

What can we define with a Class definition? -

We can define two main areas with the help of a class definition -

  • Instance Properties -
    > What an object will have.
    Example - name, color, etc.

  • Instance Methods -
    > What an object will do.
    Example - add, area, etc. ( any function )

Note: An instance is a specific representation of an object, or we can say an instance is an object created using a particular class.

Class syntax -

Let's look at the code first then we'll talk about its parts one by one -


class Person {
    constructor(personName) {
        this.name = personName; 
    } 
    sayHi() {
        console.log(`Hi ${this.name}`); 
    }
}
// Usage:
let person1 = new Person("Alok"); 
person1.sayHi(); //Output - Hi Alok

Enter fullscreen mode Exit fullscreen mode

We have to use the class keyword to create a class, followed by a class name that conventionally starts with a capital letter, i.e., Person in the above code.

The class definition goes between two curly braces {}.

Every class has a constructor, and a constructor is basically a method that runs only once during the object's life, specifically when the object is being created.

The constructor is used to setup the object, i.e., to define the states of the object ( properties ).

In this.name = personName -

this refers to the current object which is being created.

name refers to the property name.

personName is the argument passed while creating the object.

also, sayHi() is a method with some functionality.

Let's see how we create an object using a class -

We create an object using the new keyword with a class as in this code, we have created a person1 object using the Person class.

Also, we have passed "Alok" as an argument to the constructor method while creating the object.

We have called the sayHi() method using person1.sayHi(), which runs the code inside the method and gives output Hi Alok.

Let’s see one more example -


class Rectangle {
  constructor(length, breadth) {
    this.length = length;
    this.breadth = breadth;
  }

  area() {
    return this.length * this.breadth;
  }
}

let rectangle1 = new Rectangle(4, 5);
rectangle1.area(); // gives Output: 20

Enter fullscreen mode Exit fullscreen mode

In this example, we have created a rectangle1 object with arguments 4 and 5.

area() method uses these arguments stored in properties to find the area( length*breadth ) and return it.


getters and setters

Getters and Setters are basically used to define methods in a class and then used as if they are properties.

Let's understand these with an example -


class Square {
  constructor(side) {
    this.side = side;
  }

  get area() {
    return this.side * this.side;
  }

  set area(area) {
    this.side = Math.sqrt(area);
  }
}

let square1 = new Square(4);
console.log(square1.area); // gives output: 16
square1.area = 25;
console.log(square1.side); // gives output: 5

Enter fullscreen mode Exit fullscreen mode

To use a getter, we have to use the get keyword and then define the method, and we can call it as a property ( square1.area - notice we don't have () while calling the area method ).

While to use a setter, we use the set keyword and then define the method, and we call it by directly assigning the argument to it as we do in a property ( square1.area = 25 - notice we don't pass the argument here; instead assign it directly ).


static methods

Static methods are defined in the class but are not used by or part of the created object.

Or, in simple words, static methods don't require an instance of a class to be created in order to be used.

Static methods are also called helper methods.

Let's understand this with an example -


class Temp {
  constructor() {
  }

  static isEqual(a, b) {
    return a === b;
  }
}

Temp.isEqual(4,5); // returns false
Temp.isEqual(4,4); // returns true

Enter fullscreen mode Exit fullscreen mode

A static method is defined using a static keyword followed by a method definition ( i.e. static isEqual() ).

A static method can be called directly using the class name ( i.e. Temp.isEqual() ).

As you can see above, we don't need to create an object to use the static method.

Also, we can pass objects while calling a static method.

Let's see an example -


class Temp {
  constructor(value) {
    this.value = value;
  }

  static isEquals(Obj1, Obj2) {
    return Obj1.value === Obj2.value;
  }
}

let temp1 = new Temp(4);
let temp2 = new Temp(6);
let temp3 = new Temp(4);

Temp.isEquals(temp1,temp2); // returns false
Temp.isEquals(temp1,temp3); // returns true

Enter fullscreen mode Exit fullscreen mode

Here you can see we have passed objects as arguments to a static method, which is called directly using the class name.

Then the method accesses each value property using objectName.value and returns the result.


inheritance and extends

With the help of inheritance, a class can extend another class. Or, in simpler words, one class can have access to methods of another class and also have its own methods.

Let's understand this with the help of this picture -

inheritance and extends

In the above picture, a Child class extends a Parent class. As we can see, the Child class has access to the methods of the Parent class ( i.e., add() and multiply() ); also, it has its own methods( i.e., divide() and area() ).

Let's understand inheritance with the help of an example.

Have a look at the code first then we'll talk about its parts one by one -


class Person {
  constructor(name, age) {
    this.name = name;
    this.age = age;
  }

  sayHi() {
    console.log(`Hi!!! this is ${this.name} and I'm ${this.age} years old.`);
  }
}

class Programmer extends Person {
  constructor(name, age, role) {
    super(name, age);
    this.role = role;
  }

  info() {
    this.sayHi();
    console.log(`And I'm a ${this.role}`);
  }
}

let person1 = new Person("Aman", 20);
let programmer1 = new Programmer("Alok", 21,
 "Web Developer");

Enter fullscreen mode Exit fullscreen mode

Here we have a Person class that has a constructor taking arguments - name and age. Also, it has a method named sayHi() which basically console.log out "Hi!!! this is name and I'm age years old. ( name and age are arguments passed while creating an object ).

Next, we have another class named Programmer. And a class can inherit another class using extend keyword followed by the class name to be inherited. As here, the Programmer class extends Person Class.

The programmer class has a constructor taking arguments name, age, and role. The super keyword is used to call the constructor of the Person class. And now it has the Person class properties and also its own property - role.

The Programmer class has a method info() which calls the Person class method - sayHi() ( as now the Programmer class can access the Person class ). And also, console.log out "And I'm a role" ( role is an argument passed while creating an object ).

We have also created two objects person1 and programmer1, one each of the Person and Programmer Class.

Now let's have a look at different operations on them and their results -

  • example

Here you can see the programmer1 object has properties of Person class - name and age. Also, it’s own property - role.

  • example

Here we have called the sayHi() method using the object of the Person class.

  • example

Here we have called the info() method using the object of the Programmer class, and you can see it called and executed the sayHi() method of the Person class with arguments passed while creating the programmer1 object; also, it executed its own console.log out.

  • example

Here you can see we have called the sayHi() method of the Person class using the object of the Programmer Class ( as the Programmer class extends the Person class and has access to its methods ). Also, it takes arguments passed while creating progammer1 as we have called the sayHi() method using the object of the Programmer class.

  • example

But we can't access the method of the Programmer class using the object of the Person class as the Parent class doesn't have access to the Child class.


polymorphism

Polymorphism allows us to override the method of the Parent Class.

Let's understand it with the help of an example -


class Animal {
  constructor(name) {
    this.name = name;
  }

  sayName() {
    console.log(`${this.name} is an Animal.`);
  }
}

class Dogs extends Animal {
  constructor(name) {
    super(name);
  }

  sayName() {
    console.log(`${this.name} is a Dog.`);
  }
}

let animal1 = new Animal("Tiger");
let dog1 = new Dogs("Bull Dog");

Enter fullscreen mode Exit fullscreen mode

Here both the Parent Class ( Animal ) and the Child Class ( Dog ) have the same method sayName().

And we have seen earlier that we can call a Parent class method using an object of a Child class, but in this case, both the methods have the same name.

Let's see what happens when we call them -

  • example

It works fine as it should; now, let's see what happens when we call the sayName() method using dog1 object -

  • example

Here you can see the sayName() method of the Dog class overrides the sayName() method of Animal Class.

And this is how Polymorphism allows overriding the Parent class method.


I have tried to keep it simple and precise, thanks for reading it till last, and also I have a lot planned for the future So stay tuned πŸ™‚

If you find this useful then you can share it with others :)

Feel free to drop a Hi and let's chat πŸ‘‹πŸ‘‹πŸ‘‹


Read the next blog in the series
             Getting Started with JavaScript Modules πŸ‘‰

Latest comments (5)

Collapse
 
thecoollearner profile image
Alok Kumar

Thanks aman πŸ˜€

You can check out my other articles too, I bet you'd like them too :)

Collapse
 
big0290 profile image
B!G_Logical

Good explanation great work ..

Collapse
 
thecoollearner profile image
Alok Kumar

Thanks a lot πŸ™
I have planned more such articles, so stay tuned πŸ˜€

Collapse
 
yegnasivasai profile image
Yegna Sivasai

Thank you

Thread Thread
 
thecoollearner profile image
Alok Kumar

Thanks Yegna for reading :)