Unlocking the Power of JavaScript Classes
Designing with Intention
In the world of JavaScript, classes offer a powerful way to craft blueprints for objects, mirroring the traditional object-oriented programming languages like C++ or Java. Let’s dive into a simple example by creating a Person
class:
“`
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
greet() {
console.log(Hello, my name is ${this.name} and I am ${this.age} years old.
);
}
}
const person1 = new Person(‘Jack’, 30);
const person2 = new Person(‘Tina’, 33);
person1.greet(); // Output: Hello, my name is Jack and I am 30 years old.
person2.greet(); // Output: Hello, my name is Tina and I am 33 years old.
“`
Flexibility Unleashed
JavaScript provides the flexibility to create objects directly, without the need for formal class definitions. This can be achieved through the use of object literals. Let’s explore an example:
“
Hello, my name is ${this.name} and I am ${this.age} years old.`);
const person = {
name: 'Jack',
age: 30,
greet() {
console.log(
}
};
person.greet(); // Output: Hello, my name is Jack and I am 30 years old.
“`
Dissecting JavaScript Classes
Now, let’s revisit the code and delve deeper into each part to gain a richer understanding of how classes work in JavaScript.
Creating a Class
In JavaScript, we create a class using the class
keyword. This defines a blueprint for objects, outlining their properties and behaviors.
The Class Constructor
A class constructor is a special method within a class that is automatically executed when a new object of that class is created. It initializes the object’s properties, setting the stage for its behavior.
Class Methods
A class method is a function inside a class that defines behaviors for the class’s objects. In our Person
class, the greet()
method displays a personalized greeting message when called on objects of the class.