Creating a class in JavaScript using the class
keyword, introduced in ECMAScript 6 (ES6), provides a clean and concise way to define object blueprints. This modern syntax enhances the readability and structure of the code, making it more intuitive, especially for developers transitioning from other object-oriented programming languages. Let's dive deeper into creating and using classes in JavaScript, along with a practical example.
Basic Structure of a JavaScript Class
Below is a basic example demonstrating how to create a class, define a constructor, and add methods.
// Define a class
class Person {
// Constructor method to initialize the object
constructor(name, age) {
this.name = name;
this.age = age;
}
// Method to return the person's name
getName() {
return this.name;
}
// Method to return the person's age
getAge() {
return this.age;
}
// Method to set the person's name
setName(newName) {
this.name = newName;
}
// Method to set the person's age
setAge(newAge) {
this.age = newAge;
}
// Method to return a greeting
greet() {
return `Hello, my name is ${this.name} and I am ${this.age} years old.`;
}
}
// Create an instance of the class
const person1 = new Person('John Doe', 30);
// Access the instance methods and properties
console.log(person1.getName()); // Output: John Doe
console.log(person1.getAge()); // Output: 30
console.log(person1.greet()); // Output: Hello, my name is John Doe and I am 30 years old.
// Modify the instance properties
person1.setName('Jane Doe');
person1.setAge(25);
console.log(person1.greet()); // Output: Hello, my name is Jane Doe and I am 25 years old.(code-box)
Explanation
- Class Definition: The
Person
class is defined using theclass
keyword. This creates a blueprint for objects that will havename
andage
properties. - Constructor: The
constructor
method is a special method for initializing an object created with a class. In this example, it initializes thename
andage
properties. - Methods:
getName
and getAge
: Methods to return the name
and age
properties, respectively.
setName
and setAge
: Methods to update the name
and age
properties, respectively.greet
: A method that returns a greeting message.
- Instance Creation: An instance of the
Person
class is created using thenew
keyword. The methods are accessed using dot notation.
Inheritance
In JavaScript, you can create sub classes that inherit from a parent class using the extends
keyword. This allows the subclass to access and modify properties and methods of the parent class. The super
keyword is used to call the parent class's constructor.
// Define a subclass that extends the Person class
class Employee extends Person {
constructor(name, age, jobTitle) {
super(name, age); // Call the parent class's constructor
this.jobTitle = jobTitle;
}
// Method to return the employee's job title
getJobTitle() {
return this.jobTitle;
}
// Method to set the employee's job title
setJobTitle(newJobTitle) {
this.jobTitle = newJobTitle;
}
// Override the greet method to include the job title
greet() {
return `Hello, my name is ${this.name}, I am ${this.age} years old and I work as a ${this.jobTitle}.`;
}
}
// Create an instance of the subclass
const employee1 = new Employee('Alice Johnson', 28, 'Software Developer');
console.log(employee1.greet()); // Output: Hello, my name is Alice Johnson, I am 28 years old and I work as a Software Developer.(code-box)
Explanation of Inheritance Example
- Subclass Definition: The
Employee
class extends thePerson
class, inheriting its properties and methods. - Constructor: The constructor in the
Employee
class calls the parent class's constructor usingsuper
and initializes thejobTitle
property. - Method Overriding: The
greet
method in theEmployee
class overrides thegreet
method in thePerson
class to include thejobTitle
.
Practical Use Cases
Using classes in JavaScript is essential in larger applications, particularly in frameworks and libraries like React, Angular, and Node.js. Classes help organize code into modular, reusable components, enhancing maintainability and scalability.
Example in a Web Application
Consider a simple web application where you need to manage user data. Using classes can help encapsulate user-related logic.
class User {
constructor(username, email) {
this.username = username;
this.email = email;
}
getUsername() {
return this.username;
}
getEmail() {
return this.email;
}
setUsername(newUsername) {
this.username = newUsername;
}
setEmail(newEmail) {
this.email = newEmail;
}
userDetails() {
return `User: ${this.username}, Email: ${this.email}`;
}
}
// Example usage
const user1 = new User('jsmith', 'jsmith@example.com');
console.log(user1.userDetails()); // Output: User: jsmith, Email: jsmith@example.com
user1.setUsername('johnsmith');
user1.setEmail('johnsmith@example.com');
console.log(user1.userDetails()); // Output: User: johnsmith, Email: johnsmith@example.com(code-box)
Conclusion
Using the class
keyword in JavaScript allows for a more structured and organised approach to object-oriented programming. It makes the code more readable and maintainable, leveraging modern JavaScript features. Classes and inheritance provide powerful tools to create modular, reusable, and scalable code. This is particularly beneficial in large applications where code organisation and maintainability are crucial. Whether you are building simple scripts or complex web applications, mastering classes in JavaScript is a valuable skill that will enhance your development capabilities.