js classes

Classes serve as a starting point for the creation of objects. They encapsulate data with code that allows them to work with it.

JavaScript Classes were implemented in ECMAScript 2015, also known as ES6.

JavaScript Classes are templates for JavaScript Objects and a JavaScript class is not an object.

Syntax of a Classe in JavaScript

class declaration

A class declaration is one way to define a class. You use the class keyword with the class name to declare a class.

Use the keyword ” class ” to create a class.

//Example JS Class Syntax


class ClassName {
  // your code ...
}

//

class expression

Another way to define a class is to use a class expression. There are two types of class expressions: named and unnamed.

The following example explains class expression.

// Example js class expression

// unnamed classes
let ClassName = class {

}


// named classes
let VarName = class ClassName {

}

//

The Objects, how to use the JS classes?

You can use the class to create objects. The new keyword is used to create objects of classes. The syntax of creating objects is as follows.

// Example JS Class Object

let objName = new ClassName();

//

You can now use this object to retrieve data and methods from the class. for example, we will create a class and retrieve its data.

// Example classes and objects

class Car{

    constructor(color, model){
        this.color = color;
        this.model = model;
    }
   
   getCarDetails(){
   
   console.log(`color: ${this.color} and model: ${this.model}`);

   }

}

// create object
// pass color & model
let carObj = new Car('Red', 2000);

// using this object we can call methods inside Car class.
carObj.getCarDetails();


// Outpot: color: Red and model: 2000

//

Copy and paste this code to your browser console. you will get the results.

Consider constructor() as part of JS Class syntax.

So far we have seen the basic syntax of class. now we will explain the Constructor and its importance in any class.

What is a constructor() method in Javascript? t is a special method for creating and initializing an “object” generated with a class.

When a class is created, the constructor method is called automatically, and it must have the exact name “constructor

For example

// Example of JS class constructors and JS class Syntax

class ClassName {
  
  // constructor
  constructor() { 

   // your code ...

  }

}

//

Similar Posts