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);
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);
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);
OutputAman : 25 years
Akash : 32 years
JS Classes – FAQs
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.
You can create a JavaScript class by using a predefined keyword named class before the class name.