Open In App

JS Classes In JavaScript

Last Updated : 03 Dec, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Classes in JavaScript are a blueprint for creating objects, introduced in ES6. They encapsulate data and behavior by defining properties and methods, enabling object-oriented programming. Classes simplify the creation of objects and inheritance, making code more organized and reusable.

Class In JavaScript

Creating a Simple Class

The Emp class initializes name and age properties for each new instance using a constructor.

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

const emp = new Emp("Aman", "25 years");
console.log(emp.name);
console.log(emp.age);

Output
Aman
25 years

Constructor to Initialize Objects

The constructor method is a special method used for initializing objects created with a class. It’s called automatically when a new instance of the class is created. It typically assigns initial values to object properties using parameters passed to it. This ensures objects are properly initialized upon creation.

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

const p1 = new Person("Alice", 30);
console.log(p1.name);
console.log(p1.age);

const p2 = new Person("Bob", 25);
console.log(p2.name);
console.log(p2.age);

Output
Alice
30
Bob
25

Creating Multiple Objects with a Class

Creating multiple objects with shared properties and methods.

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

const e1 = new Emp("Aman", "25 years");
const e2 = new Emp("Akash", "32 years");

console.log(e1.name + " : " + e1.age);
console.log(e2.name + " : " + e2.age);

Output
Aman : 25 years
Akash : 32 years

JS Classes – FAQs

Classes and Objects in JavaScript

Classes in JavaScript provide blueprints for creating objects with similar properties and methods. Objects are instances of classes. Classes encapsulate data and behavior, promoting code reusability and organization. Objects created from classes can have unique data but share the same methods defined in the class blueprint.

How to create a JavaScript class in ES6?

You can create a JavaScript class by using a predefined keyword named class before the class name. 



Next Article

Similar Reads

three90RightbarBannerImg
  翻译: