Javascript Class

Working with classes in Javascript

About Javascript Class

  • Classes are a template for creating objects.
  • They encapsulate data with code to work on that data.
  • Classes are just like funcitons in javascript with special syntax.

Why to use Javascript Classes?

  • To encapsulate all related code
  • To reuse properties and methods in other classes via inheritance.
  • Better maintainability

Class Syntax

class ClassName {
  constructor() { ... }
}

Example class Country

class Country {
    constructor(name, population){
        this.name = name;
        this.population = population;
    }
}

console.log(typeof Country);
// function
  • In above code we have create a class which is template to represent a country.
  • constuctor is special method which runs every time when an object is created for a given class.
  • this is special keyword which represents the instance of javascript class object.

Creating object for a javascript class

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

    // method to get full name
    getFullName(){
        return this.firstName + " " + this.lastName;
    }

    // method to check if person is adult
    isAdult(){
        if(this.age >= 18){
            return true;
        }else{
            return false;
        }
    }
}

// create object for above class
let john = new Person("John", "Bocasta", 45)
console.log(john.getFullName())
// John Bocasta
console.log(john.isAdult())
// true

// create another object for same class
let nani = new Person("Nani", "Ch", 8)
console.log(nani.getFullName())
// Nani Ch
console.log(nani.isAdult())
// false
  • In above code we have define a person class and created two different objects
  • new is keyword used to create an object for a class.

Reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes