JavaScript Classes
JavaScript classes, introduced in ECMAScript 6 (ES6), provide a way to define reusable blueprints for creating objects with specific properties and methods. While JavaScript is a prototype-based language, classes offer a cleaner and more familiar syntax for object-oriented programming (OOP). This article will guide you through JavaScript classes, including their structure, methods, and usage with examples.
1. Defining a JavaScript Class
A class is defined using the class
keyword, followed by the class name and a set of curly braces. The class body contains methods and a special method called constructor
, which is automatically called when a new instance of the class is created.
Basic Class Definition
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
// Method
greet() {
return `Hello, my name is ${this.name} and I am ${this.age} years old.`;
}
}
// Creating an instance of the class
const john = new Person("John", 25);
console.log(john.greet()); // Output: Hello, my name is John and I am 25 years old.
In this example, the Person
class has a constructor
that initializes the name
and age
properties. The greet()
method returns a greeting message.
2. Class Methods
Class methods are functions defined inside the class and can be called on the instances of the class. As shown in the previous example, the greet()
method is a class method.
Adding More Methods
class Car {
constructor(brand, model) {
this.brand = brand;
this.model = model;
}
// Method to get car details
getDetails() {
return `Car: ${this.brand} ${this.model}`;
}
// Method to update the car model
updateModel(newModel) {
this.model = newModel;
}
}
const myCar = new Car("Toyota", "Corolla");
console.log(myCar.getDetails()); // Output: Car: Toyota Corolla
myCar.updateModel("Camry");
console.log(myCar.getDetails()); // Output: Car: Toyota Camry
The Car
class has two methods: getDetails()
to return car details and updateModel()
to update the model of the car.
3. Class Inheritance
In JavaScript, classes can inherit from other classes using the extends
keyword. This allows a class to access the properties and methods of another class. The subclass can also override methods from the parent class.
Example of Class Inheritance
class Animal {
constructor(name) {
this.name = name;
}
speak() {
return `${this.name} makes a noise.`;
}
}
// Subclass inheriting from Animal
class Dog extends Animal {
speak() {
return `${this.name} barks.`;
}
}
const dog = new Dog("Rex");
console.log(dog.speak()); // Output: Rex barks.
In this example, the Dog
class extends the Animal
class, and it overrides the speak()
method to provide a specific implementation for dogs.
4. Static Methods
Static methods are defined using the static
keyword and can be called on the class itself, rather than on instances of the class.
Example of Static Methods
class Calculator {
static add(a, b) {
return a + b;
}
static subtract(a, b) {
return a - b;
}
}
console.log(Calculator.add(10, 5)); // Output: 15
console.log(Calculator.subtract(10, 5)); // Output: 5
In this example, the Calculator
class has two static methods, add()
and subtract()
, which can be called without creating an instance of the class.
5. Getters and Setters
Getters and setters allow you to define methods that behave like properties. Getters retrieve property values, while setters allow you to modify them.
Example of Getters and Setters
class Person {
constructor(name) {
this._name = name; // Convention to indicate private property
}
// Getter
get name() {
return this._name;
}
// Setter
set name(newName) {
this._name = newName;
}
}
const person = new Person("Alice");
console.log(person.name); // Output: Alice
person.name = "Bob"; // Using the setter to update the name
console.log(person.name); // Output: Bob
In this example, the name
property is accessed using the getter and updated using the setter.
6. Private Fields in Classes
Private fields, denoted by a #
symbol, are accessible only within the class where they are defined. This ensures that certain properties are kept private and cannot be accessed or modified from outside the class.
Example of Private Fields
class BankAccount {
#balance;
constructor(balance) {
this.#balance = balance;
}
deposit(amount) {
this.#balance += amount;
return `Deposited ${amount}, new balance: ${this.#balance}`;
}
getBalance() {
return `Current balance: ${this.#balance}`;
}
}
const account = new BankAccount(1000);
console.log(account.deposit(500)); // Output: Deposited 500, new balance: 1500
console.log(account.getBalance()); // Output: Current balance: 1500
Here, the #balance
field is private, ensuring that the balance cannot be accessed or modified directly from outside the class.
Conclusion
JavaScript classes provide a powerful and intuitive way to work with object-oriented programming concepts, such as inheritance, encapsulation, and abstraction. By using classes, you can create reusable blueprints for objects and write cleaner, more maintainable code. From defining constructors and methods to leveraging inheritance and private fields, classes bring structure to JavaScript's flexible object-oriented model.
Comments
Post a Comment