-
Hajipur, Bihar, 844101
Hajipur, Bihar, 844101
JS Basics
JS Variables & Operators
JS Data Types & Conversion
JS Numbers & Math
JS Strings
JS Dates
JS Arrays
JS Control Flow
JS Loops & Iteration
JS Functions
JS Functions
Function Definitions
Function Parameters
Function Invocation
Function Call
Function Apply
Function Bind
Function Closures
JS Arrow Function
JS Objects
JS Objects
JS Object Properties
JS Object Methods
JS Object Display
JS Object Constructors
Object Definitions
Object Get / Set
Object Prototypes
Object Protection
JS Classes & Modules
JS Async Programming
JS Advanced
JS Destructuring
JS Bitwise
JS RegExp
JS Precedence
JS Errors
JS Scope
JS Hoisting
JS Strict Mode
JS this Keyword
JS HTML DOM
DOM Intro
DOM Methods
DOM Document
DOM Elements
DOM HTML
DOM Forms
DOM CSS
DOM Animations
DOM Events
DOM Event Listener
DOM Navigation
DOM Nodes
DOM Collections
DOM Node Lists
JS BOM (Browser Object Model)
JS Web APIs
Web API Intro
Web Validation API
Web History API
Web Storage API
Web Worker API
Web Fetch API
Web Geolocation API
JS AJAX
AJAX Intro
AJAX XMLHttp
AJAX Request
AJAX Response
AJAX XML File
AJAX PHP
AJAX ASP
AJAX Database
AJAX Applications
AJAX Examples
JS JSON
JSON Intro
JSON Syntax
JSON vs XML
JSON Data Types
JSON Parse
JSON Stringify
JSON Objects
JSON Arrays
JSON Server
JSON PHP
JSON HTML
JSON JSONP
JS Graphics & Charts
JavaScript classes were introduced in ES6 (ECMAScript 2015) to provide a clear and structured way to create objects and implement object-oriented programming concepts.
While JavaScript has always been prototype-based, the class
syntax offers syntactic sugar over constructor functions and prototypes. Classes help developers write cleaner, more organized code, especially in large applications where object blueprints, inheritance, and encapsulation are required.
Understanding classes is fundamental for building scalable and maintainable JavaScript applications, and they are heavily used in modern frameworks such as React, Vue.js, and Angular.
A class in JavaScript is a blueprint for creating objects. It defines:
Properties: Data that each object will hold.
Methods: Functions that operate on the object’s data.
Unlike constructor functions, the class syntax is more readable and intuitive, clearly separating instance properties from shared methods.
The simplest class definition uses the class
keyword followed by a name and a body:
class Person {
constructor(firstName, lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
fullName() {
return `${this.firstName} ${this.lastName}`;
}
}
const person1 = new Person("Alice", "Smith");
console.log(person1.fullName()); // Alice Smith
constructor()
is a special method automatically called when an object is created using new
.
Methods defined outside the constructor are shared via the prototype, not copied to each instance.
Clear Syntax: Classes are easier to read and understand compared to constructor functions.
Encapsulation: Properties and methods are clearly grouped.
Inheritance Support: Classes provide the extends
and super()
syntax for easy inheritance.
Prototype Management: Methods are automatically added to the prototype, saving memory.
An object created using a class is called an instance. Each instance has its own unique properties, while methods are shared.
const person2 = new Person("John", "Doe");
console.log(person2.fullName()); // John Doe
Properties like firstName
and lastName
are unique to each instance.
Methods like fullName
exist once on the prototype and are accessible by all instances.
Classes can include getters and setters to control access and update properties:
class Student {
constructor(firstName, lastName, grade) {
this.firstName = firstName;
this.lastName = lastName;
this._grade = grade;
}
get grade() {
return this._grade;
}
set grade(value) {
if (value < 0 || value > 100) {
console.log("Invalid grade");
} else {
this._grade = value;
}
}
fullName() {
return `${this.firstName} ${this.lastName}`;
}
}
const student1 = new Student("John", "Doe", 90);
student1.grade = 105; // Invalid grade
console.log(student1.grade); // 90
_grade
is a private-like property (convention using underscore).
Setters allow validation before updating properties.
Static methods are class-level methods not accessible by instances.
class Calculator {
static add(a, b) {
return a + b;
}
}
console.log(Calculator.add(5, 10)); // 15
Attempting to call add
on an instance will fail.
Static methods are useful for utility functions related to the class.
JavaScript classes support inheritance, allowing one class to extend another:
class Animal {
constructor(name) {
this.name = name;
}
speak() {
console.log(`${this.name} makes a sound`);
}
}
class Dog extends Animal {
constructor(name, breed) {
super(name); // Call parent constructor
this.breed = breed;
}
speak() {
console.log(`${this.name} barks`);
}
}
const dog1 = new Dog("Rex", "Labrador");
dog1.speak(); // Rex barks
extends
creates a subclass.
super()
calls the parent class constructor.
Child classes can override parent methods.
Modern JavaScript allows true private fields and methods using the #
prefix:
class BankAccount {
#balance = 0;
deposit(amount) {
this.#balance += amount;
}
getBalance() {
return this.#balance;
}
}
const account = new BankAccount();
account.deposit(100);
console.log(account.getBalance()); // 100
Private fields cannot be accessed outside the class.
This feature improves encapsulation and security.
Use classes for structured and reusable objects.
Define instance properties in the constructor.
Place methods outside the constructor for memory efficiency.
Use getters/setters for property control.
Use static methods for utilities not tied to instances.
Use private fields for sensitive or internal data.
Classes are blueprints for creating objects in JavaScript.
They support constructors, methods, inheritance, static methods, and private fields.
Classes improve readability, maintainability, and organization compared to constructor functions.
Mastering classes is essential for modern JavaScript development, including OOP patterns and framework usage.
Proper use of classes ensures scalable and efficient code in real-world applications.
Understanding classes provides the foundation for advanced topics like inheritance, encapsulation, and object-oriented design, making JavaScript code easier to write, maintain, and scale.
Basic Class Creation
Create a class Person
with properties firstName
and lastName
. Add a method fullName()
to return the full name. Instantiate an object and log the full name.
Constructor with Multiple Properties
Create a class Student
with firstName
, lastName
, and grade
. Create two instances and log their properties.
Getters and Setters
Add a getter and setter for grade
in the Student
class to validate the grade is between 0 and 100. Test with valid and invalid values.
Static Method
Create a class Calculator
with a static method multiply(a, b)
. Call it directly from the class and verify it cannot be called on an instance.
Instance Method vs Static Method
Create a class Car
with an instance method info()
and a static method compare()
. Instantiate objects and test both methods.
Inheritance
Create a class Animal
with a method speak()
. Extend it with a class Cat
that overrides speak()
to print a custom message.
Using super()
In a child class, call the parent constructor using super()
and verify that inherited properties are correctly initialized.
Private Fields
Create a class BankAccount
with a private field #balance
. Add methods to deposit money and check balance. Attempt to access #balance
directly.
Multiple Instances Sharing Methods
Show that two instances of a class share the same method reference by comparing the function references.
Computed Method Names
Define a method in a class using a computed property name (e.g., [methodName]()
) and call it on an instance to demonstrate dynamic method definition.
JS Basics
JS Variables & Operators
JS Data Types & Conversion
JS Numbers & Math
JS Strings
JS Dates
JS Arrays
JS Control Flow
JS Loops & Iteration
JS Functions
JS Functions
Function Definitions
Function Parameters
Function Invocation
Function Call
Function Apply
Function Bind
Function Closures
JS Arrow Function
JS Objects
JS Objects
JS Object Properties
JS Object Methods
JS Object Display
JS Object Constructors
Object Definitions
Object Get / Set
Object Prototypes
Object Protection
JS Classes & Modules
JS Async Programming
JS Advanced
JS Destructuring
JS Bitwise
JS RegExp
JS Precedence
JS Errors
JS Scope
JS Hoisting
JS Strict Mode
JS this Keyword
JS HTML DOM
DOM Intro
DOM Methods
DOM Document
DOM Elements
DOM HTML
DOM Forms
DOM CSS
DOM Animations
DOM Events
DOM Event Listener
DOM Navigation
DOM Nodes
DOM Collections
DOM Node Lists
JS BOM (Browser Object Model)
JS Web APIs
Web API Intro
Web Validation API
Web History API
Web Storage API
Web Worker API
Web Fetch API
Web Geolocation API
JS AJAX
AJAX Intro
AJAX XMLHttp
AJAX Request
AJAX Response
AJAX XML File
AJAX PHP
AJAX ASP
AJAX Database
AJAX Applications
AJAX Examples
JS JSON
JSON Intro
JSON Syntax
JSON vs XML
JSON Data Types
JSON Parse
JSON Stringify
JSON Objects
JSON Arrays
JSON Server
JSON PHP
JSON HTML
JSON JSONP
JS Graphics & Charts