- Courses
- đ»Programming Languages
- đJavaScript
- Objects and Classes
- Classes
On this page
JavaScript Classes
By Enrico Hochkoeppler
Web Developer & TutoriaLibre Founder
While JavaScript remains a prototypal language at its core, the introduction of the Class syntax in ECMAScript 2015 (ES6) provided a much cleaner and more familiar abstraction for developers coming from class-based languages. Classes serve as blueprints for creating objects, encapsulating data and the behavior that operates on that data into a single, cohesive unit.
Class Declaration and the Constructorâ
A class is defined using the class keyword followed by an identifier. The most critical part of a class is the constructor method. The constructor is a special method that executes automatically when a new instance of the class is created. It is primarily used to initialize the object's properties.
class User {
constructor(name, email) {
this.name = name;
this.email = email;
}
}
const user1 = new User("Alice", "[email protected]");
When the new keyword is used, a new empty object is created, the this context is bound to that object, and the constructor function is invoked to populate it.
Defining Methodsâ
Methods are functions defined inside the class body that describe the behavior of the objects created from that class. Unlike traditional function declarations, you do not use the function keyword when defining methods inside a class.
These methods are automatically added to the class's prototype, ensuring that all instances share a single copy of the method to save memory.
class User {
constructor(name, email) {
this.name = name;
this.email = email;
}
// Instance Method
displayProfile() {
console.log(`User: ${this.name} | Email: ${this.email}`);
}
}
const user1 = new User("Alice", "[email protected]");
user1.displayProfile();
Inheritance with the Extends Keywordâ
Inheritance allows one class to derive properties and methods from another. This promotes code reuse and creates a hierarchical relationship between classes. To implement inheritance, JavaScript uses the extends keyword.
The Super Keywordâ
When a child class (subclass) inherits from a parent class (superclass), it often needs to access the parent's constructor or methods. The super keyword is used for two specific purposes:
- In the Constructor: It calls the parent class's constructor. This must be called before accessing
thisin the child constructor. - In Methods: It can be used to call methods defined on the parent class.
class Employee extends User {
constructor(name, email, role) {
// Call the parent constructor
super(name, email);
this.role = role;
}
displayWorkInfo() {
// Accessing parent properties via 'this'
console.log(`${this.name} works as a ${this.role}`);
}
}
const emp1 = new Employee("Bob", "[email protected]", "Developer");
emp1.displayProfile(); // Inherited method
emp1.displayWorkInfo(); // Child-specific method
Method Overridingâ
A child class can provide a specific implementation of a method that is already defined in its parent class. This is known as Method Overriding. When the method is called on an instance of the child class, the childâs version is executed instead of the parent's.
class Admin extends User {
displayProfile() {
console.log(`ADMIN ACCOUNT: ${this.name}`);
}
}
const admin1 = new Admin("Charlie", "[email protected]");
admin1.displayProfile(); // Output: ADMIN ACCOUNT: Charlie
Static Methodsâ
Sometimes a method belongs to the class itself rather than to any specific instance. By using the static keyword, you define a method that is called directly on the class name. Static methods are often used for utility functions, such as creating or cloning objects.
class Helper {
static identify() {
console.log("This is a User Management System Helper.");
}
}
Helper.identify(); // Called on the class, not an instance
Professional Implementation Standardsâ
To utilize classes effectively in a production environment, follow these structural guidelines:
- PascalCase Naming: Always name your classes using PascalCase (e.g.,
userProfileis an object,UserProfileis a class). - Strict Mode: The body of a class always executes in Strict Mode, even if you haven't explicitly declared it. This prevents common errors like accidental global variable creation.
- Encapsulation: Use classes to hide internal logic. If a piece of data is only relevant to the internal workings of the class, it should be kept there rather than exposed globally.
- Favor Composition: While inheritance is powerful, avoid deep inheritance chains (e.g., a class inheriting from a class which inherits from another). Deep hierarchies can make code difficult to track and maintain.
Found this helpful? Share the knowledge...
... or support this project to keep it alive!
Previous
Prototypes & Inheritance
Next
Encapsulation & Private Fields
-
Class Declaration and the Constructor
-
Defining Methods
-
Inheritance with the Extends Keyword
- The Super Keyword
-
Method Overriding
-
Static Methods
-
Professional Implementation Standards
