JavaScript Class Fundamentals: Explained with examples

A class is a blueprint for the object. You can create an object from the class. They encapsulate data with code to work on that data. Classes in JS are built on prototypes but also have some syntax and semantics that are not shared with ES5 class-like semantics.

You can think of the class as a sketch (prototype) of a house. It contains all the details about the floors, doors, windows, etc. Based on these descriptions, you build the house. House is the object.

Syntax

        
class MyClass {
    // class methods
    constructor() { ... }
    method1() { ... }
    method2() { ... }
    method3() { ... }
  ...
}
        
    

Example

        
// creating a class

class Person {
    constructor(name) {
        this.name = name;
        }
    }
      
// creating an object
const person1 = new Person('Ankit');
const person2 = new Person('Patel');

console.log(person1.name);      // Output : John
console.log(person2.name);      // Output : Jack
 
        
    

In the above example, class is declaring using class keyword. Then we create object to access its value. Person1 & person2 are object of class person.

Class Methods

It is easy to define methods in the JavaScript class. You simply give the name of the method followed by ()

 

        
class Person {
    constructor(name) {
    this.name = name;
}
               
// defining method
greet() {
    console.log(`Hello ${this.name}`);
}
}

let person1 = new Person('John');
// accessing property

console.log(person1.name); // John
        
    
Posted in

Ankit Patel

Leave a Comment

Your email address will not be published.

Scroll to Top