A JavaScript class is a blueprint for creating objects. It allows developers to define properties and methods in a single structure, making code more organized, reusable, and easier to maintain.
Introduced in ES6, classes provide a structured way to create objects with shared properties and methods.
They support object-oriented programming concepts such as inheritance, encapsulation, and modularity.
Javascript Class
Syntax
class ClassName {
constructor() {
// Initialize properties here
}
// Define methods here
methodName() {
// Method code
}
}
The constructor() method is a special method that is automatically called when an instance of the class is created.
You can define methods inside the class to provide behaviour for objects created from the class.
Key Features of JavaScript Classes
Encapsulation: Bundles data (properties) and behaviour (methods) together.
Constructor Method: Initializes properties when an object is created.
Inheritance: Allows one class to inherit properties and methods from another.
Code Reusability: Enables the creation of multiple instances with shared functionality.
Simplicity & Clarity: Provides a clear structure for creating and managing objects.
Creating a Simple Class
A basic class that defines properties and methods. This example shows how to create an object with a constructor and method.
JavaScript
classPerson{constructor(name,age){this.name=name;this.age=age;}g(){console.log(`Hello, my name is ${this.name} and I am ${this.age} years old.`);}}letp1=newPerson("Pranjal",20);p1.g();
The Person class has a constructor to set name and age, and a g method to log a greeting message.
An instance (p1) is created with new, passing "Pranjal" and 20, then calls g to print the greeting.
Constructor to Initialize Objects
The constructor is used to initialize the properties of the object when an instance is created.
You are visitor 01402503 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.