Understanding Classes in JavaScript: Functions, Methods, Access Modifiers, and Lifecycle
August 30th, 2024 12:14 PM Mr. Q Categories: JavaScript
Class Functions and Methods
1. Class Functions
In JavaScript, functions defined within a class are generally referred to as methods. These methods define the behaviors of the class’s instances and can be used to perform actions or return values based on the class’s state.
class MyClass {
myFunction() {
console.log("This is a class function.");
}
}
const instance = new MyClass();
instance.myFunction(); // Output: This is a class function.
- Class Definition:
class MyClass
: This line defines a class namedMyClass
.myFunction()
: This method is part ofMyClass
and outputs a message to the console.
- Instance Creation:
const instance = new MyClass()
: Creates a new instance ofMyClass
, namedinstance
.
- Method Invocation:
instance.myFunction()
: Calls themyFunction
method on theinstance
object, which prints “This is a class function.” to the console.
This example highlights how methods within a class provide functionality to instances of the class, allowing them to perform actions or retrieve values based on their internal state.
2. Methods
Methods are special functions associated with class instances. They are used to interact with the instance’s properties and perform operations.
class Person {
constructor(name) {
this.name = name;
}
greet() {
console.log(`Hello, my name is ${this.name}.`);
}
}
const person = new Person("Alice");
person.greet(); // Output: Hello, my name is Alice.
- Class Definition:
class Person
: Defines a class namedPerson
.constructor(name)
: A special method used to initialize new instances of the class. It sets thename
property of the instance to the value provided when the instance is created.greet()
: A method that logs a greeting message to the console using the instance’sname
property.
- Instance Creation:
const person = new Person("Alice")
: Creates a new instance of thePerson
class, initializing it with the name"Alice"
.
- Method Invocation:
person.greet()
: Calls thegreet
method on theperson
instance. This method accesses thename
property of the instance and prints “Hello, my name is Alice.” to the console.
This example demonstrates how methods can be used to perform operations and interact with the properties of an instance, enabling dynamic behavior based on the instance’s state.
Private and Public Access Modifiers
1. Public Members
By default, all properties and methods in JavaScript classes are public. This means they can be accessed and modified from outside the class.
class Car {
constructor(make, model) {
this.make = make;
this.model = model;
}
displayInfo() {
console.log(`Car: ${this.make} ${this.model}`);
}
}
const car = new Car("Toyota", "Camry");
car.displayInfo(); // Output: Car: Toyota Camry
Class Definition:
class Person
: Defines a class namedPerson
.constructor(name)
: A special method that initializes new instances of the class. It sets thename
property of the instance to the value provided during instance creation.greet()
: A method that logs a greeting message to the console using the instance’sname
property.
Instance Creation:
const person = new Person("Alice")
: Creates a new instance of thePerson
class and initializes it with the name"Alice"
.
Method Invocation:
person.greet()
: Calls thegreet
method on theperson
instance. This method accesses thename
property and prints"Hello, my name is Alice."
to the console.
This example demonstrates how methods in a class can perform actions and interact with the class’s properties. Methods enable objects to exhibit dynamic behavior based on their state, making classes a powerful tool for creating and managing complex structures and behaviors in JavaScript.
2. Private Members
Private members are only accessible within the class itself. They are declared using the #
symbol before the property or method name. This feature helps encapsulate the internal state of the class.
class Car {
#speed; // Private field
constructor(make, model) {
this.make = make;
this.model = model;
this.#speed = 0;
}
accelerate(amount) {
this.#speed += amount;
console.log(`Accelerated to ${this.#speed} km/h`);
}
}
const car = new Car("Toyota", "Camry");
car.accelerate(50); // Output: Accelerated to 50 km/h
console.log(car.#speed); // Error: Private field '#speed' must be declared in an enclosing class
- Private Field Definition:
#speed
: Declaresspeed
as a private field. This means it is only accessible within theCar
class.
- Constructor:
constructor(make, model)
: Initializes themake
,model
, and#speed
properties of theCar
instance. The#speed
is set to0
.
- Method:
accelerate(amount)
: Increases the value of the private#speed
field by theamount
provided and logs the new speed.
- Instance Creation and Method Invocation:
const car = new Car("Toyota", "Camry")
: Creates a new instance ofCar
.car.accelerate(50)
: Calls theaccelerate
method, which modifies the private#speed
field and logs the updated speed.
- Private Access Error:
console.log(car.#speed)
: Attempts to access the private#speed
field directly from outside the class, which results in an error. This error occurs because private fields cannot be accessed outside the class they are defined in.
Private members provide a way to encapsulate data within a class, protecting it from being accessed or modified directly from outside the class. This helps maintain the integrity of the class’s internal state and ensures that its behavior is controlled through its public methods.
Constructor
The constructor is a special method used to initialize new objects created from a class. It is automatically called when a new instance of the class is created.
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
introduce() {
console.log(`Hi, I'm ${this.name} and I'm ${this.age} years old.`);
}
}
const person = new Person("John", 30);
person.introduce(); // Output: Hi, I'm John and I'm 30 years old.
- Class Definition:
class Person
: Defines a class namedPerson
.
- Constructor Method:
constructor(name, age)
: A special method that initializes new instances of thePerson
class. It takes two parameters,name
andage
, and sets these values as properties on the instance.
- Instance Creation:
const person = new Person("John", 30)
: Creates a new instance ofPerson
, initializing it with the name"John"
and age30
.
- Method:
introduce()
: A method that logs a message to the console, introducing the person by name and age.
- Method Invocation:
person.introduce()
: Calls theintroduce
method on theperson
instance, which outputs “Hi, I’m John and I’m 30 years old.” to the console.
The constructor method in JavaScript classes allows you to initialize new objects with specific values when they are created. It sets up the initial state of the object and ensures that properties are ready for use when the object is first instantiated.
Initializer
In JavaScript classes, initializers refer to default values or setup code executed when an instance is created. These are typically handled within the constructor
.
class BankAccount {
constructor(owner, balance = 0) {
this.owner = owner;
this.balance = balance; // Default initializer
}
displayBalance() {
console.log(`Balance for ${this.owner}: $${this.balance}`);
}
}
const account = new BankAccount("Alice");
account.displayBalance(); // Output: Balance for Alice: $0
Class Definition:
class Person
: Defines a class namedPerson
.
Constructor Method:
constructor(name, age)
: A special method that initializes new instances of thePerson
class. It takes two parameters,name
andage
, and sets these values as properties on the instance.
Instance Creation:
const person = new Person("John", 30)
: Creates a new instance ofPerson
, initializing it with the name"John"
and age30
.
Method:
introduce()
: A method that logs a message to the console, introducing the person by name and age.
Method Invocation:
person.introduce()
: Calls theintroduce
method on theperson
instance, which outputs"Hi, I'm John and I'm 30 years old."
to the console.
The constructor method in JavaScript classes enables the initialization of new objects with specific values when they are created. It sets up the object’s initial state and ensures that its properties are ready for use immediately after instantiation.
Destructor
JavaScript does not have a formal destructor mechanism like some other programming languages. However, you can implement cleanup logic in a method that can be called explicitly to perform any necessary finalization.
class Resource {
constructor(name) {
this.name = name;
console.log(`${this.name} resource initialized.`);
}
cleanUp() {
console.log(`${this.name} resource cleaned up.`);
}
}
const resource = new Resource("MyResource");
resource.cleanUp(); // Output: MyResource resource cleaned up.
- Class Definition:
class Resource
: Defines a class namedResource
.
- Constructor Method:
constructor(name)
: Initializes a new instance ofResource
with a givenname
. It logs a message indicating that the resource has been initialized.
- Cleanup Method:
cleanUp()
: A method designed to handle cleanup or finalization tasks. It logs a message indicating that the resource has been cleaned up.
- Instance Creation and Method Invocation:
const resource = new Resource("MyResource")
: Creates a new instance ofResource
with the name"MyResource"
, initializing it and logging the initialization message.resource.cleanUp()
: Explicitly calls thecleanUp
method on theresource
instance, which logs the cleanup message.
While JavaScript lacks a built-in destructor mechanism, you can manage cleanup tasks by defining a dedicated method within your class. This method can be called explicitly when you need to release resources or perform finalization tasks, ensuring that any necessary cleanup is handled appropriately.
Private Methods
Private methods are functions that can only be accessed within the class. They are declared using the #
symbol, similar to private fields. These methods help encapsulate internal logic that should not be exposed outside the class.
class Account {
#calculateInterest(amount) { // Private method
return amount * 0.05;
}
constructor(balance) {
this.balance = balance;
}
applyInterest() {
const interest = this.#calculateInterest(this.balance);
this.balance += interest;
console.log(`New balance with interest: $${this.balance}`);
}
}
const account = new Account(1000);
account.applyInterest(); // Output: New balance with interest: $1050
console.log(account.#calculateInterest(1000)); // Error: Private method '#calculateInterest' is not accessible outside class
Class Definition:
class Resource
: Defines a class namedResource
.
Constructor Method:
constructor(name)
: Initializes a new instance ofResource
with a givenname
. It logs a message indicating that the resource has been initialized.
Cleanup Method:
cleanUp()
: A method designed to handle cleanup or finalization tasks. It logs a message indicating that the resource has been cleaned up.
Instance Creation and Method Invocation:
const resource = new Resource("MyResource")
: Creates a new instance ofResource
with the name"MyResource"
, initializing it and logging the initialization message.resource.cleanUp()
: Explicitly calls thecleanUp
method on theresource
instance, which logs the cleanup message.
While JavaScript does not have a built-in destructor mechanism, you can handle cleanup tasks by defining a specific method within your class. This method should be called explicitly when resources need to be released or finalization tasks need to be performed, ensuring proper management and cleanup of resources.
In JavaScript, classes offer a powerful way to manage and structure your code. Key concepts include:
- Class Functions and Methods: Define the behaviors of class instances.
- Public and Private Members: Manage access control to class properties and methods.
- Constructor: Initializes new objects with default values.
- Initializer: Sets up default values or initial setup code.
- Destructor: JavaScript lacks formal destructors, but cleanup can be handled manually.
- Private Methods: Encapsulate internal logic within a class.
By understanding these components, you can create well-structured and encapsulated JavaScript classes, leading to more maintainable and efficient code.