6.1 Class Constructors
Constructors and methods of classes are the main elements of object-oriented programming in JavaScript. They allow you to create and initialize objects and define their behavior. Below we'll look at how constructors and methods of classes work, and how to use them.
What is a constructor?
A constructor is a special method of a class that's called when a new instance of the class is created. It's used to initialize the object, set its properties, and perform other startup tasks.
Defining a constructor
A constructor is defined using the constructor
keyword. Inside the constructor, you can use
the this
keyword to access the object's properties and methods.
Syntax:
class ClassName {
constructor(parameters) {
// Initialize the object
}
}
Example:
In the Person
class, the constructor
method takes two parameters: name
and age
.
These parameters are used to initialize the name
and age
properties of the created object.
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
}
const person1 = new Person('Alice', 30);
const person2 = new Person('Bob', 25);
console.log(person1.name); // Outputs: Alice
console.log(person2.age); // Outputs: 25
Default Constructor
If a constructor is not explicitly defined, JavaScript automatically creates an empty default constructor.
Example:
class Animal {}
const animal = new Animal();
console.log(animal); // Outputs the contents of the Animal class {}
4.2 Class Methods
Class methods are defined within the class body and provide functionality for objects created by this class. Methods are automatically added to the class prototype, allowing all instances of the class to inherit and use them.
Syntax:
class ClassName {
constructor(parameters) {
// Initialize the object
}
method1() {
// Method body
}
method2() {
// Method body
}
}
Example:
class Car {
constructor(brand, model) {
this.brand = brand;
this.model = model;
this.mileage = 0;
}
drive(distance) {
this.mileage += distance;
console.log(`${this.brand} ${this.model} drove ${distance} miles. Total mileage: ${this.mileage}`);
}
getDetails() {
return `${this.brand} ${this.model}, Mileage: ${this.mileage}`;
}
}
const myCar = new Car('Toyota', 'Camry');
myCar.drive(50); // "Toyota Camry drove 50 miles. Total mileage: 50"
console.log(myCar.getDetails()); // "Toyota Camry, Mileage: 50"
Explanation:
- The
Car
class defines two methods:drive()
andgetDetails()
- The
drive()
method increases the car's mileage and outputs info about the distance traveled - The
getDetails()
method returns a string with information about the car
6.3 Private Methods
With the introduction of new ECMAScript specifications, it's possible to create private methods and properties that are not accessible outside the class. This is done using the # symbol as part of the name.
Example of private methods and properties:
class BankAccount {
#balance = 0;
constructor(initialBalance) {
this.#balance = initialBalance;
}
#validateAmount(amount) {
if (amount <= 0) {
throw new Error('Amount must be positive.');
}
}
deposit(amount) {
this.#validateAmount(amount);
this.#balance += amount;
console.log(`Deposited ${amount}. New balance: ${this.#balance}`);
}
withdraw(amount) {
this.#validateAmount(amount);
if (amount > this.#balance) {
throw new Error('Insufficient funds.');
}
this.#balance -= amount;
console.log(`Withdrew ${amount}. New balance: ${this.#balance}`);
}
getBalance() {
return this.#balance;
}
}
const account = new BankAccount(100);
account.deposit(50); // Outputs: Deposited 50. New balance: 150
account.withdraw(30); // Outputs: Withdrew 30. New balance: 120
console.log(account.getBalance()); // Outputs: 120
// Attempting to access a private method or property will cause an error
account.#balance; // SyntaxError
account.#validateAmount(50); // SyntaxError
GO TO FULL VERSION