Introduction:
Classes are a key feature of Object-Oriented Programming (OOP) in JavaScript, introduced in ECMAScript 2015 (ES6). They provide a more intuitive and structured way to define objects and their behavior. In this blog post, we'll delve into the concept of classes in JavaScript and demonstrate their usage through practical examples.
Understanding Classes:
Classes in JavaScript act as blueprints for creating objects with predefined properties and methods. They encapsulate data and behavior within a single unit, making code organization and reuse easier.
Exploring the Code:
Let's break down the provided code snippet:
1. Class Declaration:
We declare a class named Person
using the class
keyword. This class represents a person and has a constructor method to initialize its properties name
and age
when a new instance is created.
// Class
class Person {
constructor(_name, _age) { // Constructor with parameters
this.name = _name;
this.age = _age;
}
}
2. Creating an Instance:
We create a new instance of the Person
class using the new
keyword and passing "Manikandan" as the name and 25 as the age.
const person1 = new Person("Manikandan", 25);
3. Logging the Object:
We log the person1
object to the console, which displays the properties name
and age
associated with it.
console.log(person1) // Output: Person { name: 'Manikandan', age: 25 }
4. Defining a Class with Methods:
We declare a class named Car
, which represents a car. It has a constructor method to initialize its properties name
and color
, along with a method drive()
to simulate driving the car.
class Car {
constructor(_name, _color) { // Constructor with parameters
this.name = _name;
this.color = _color;
}
drive() {
console.log(`Hi, This is My ${this.name} car. And its color is ${this.color}`)
}
}
5. Creating an Instance:
We create a new instance of the Car
class, passing "Rolls Royce" as the name and 'Black' as the color.
const car1 = new Car("Rolls Royce", 'Black');
6. Logging the Object:
We log the car1
object to the console, which displays the properties name
and color
associated with it.
console.log(car1) // Output: Car { name: 'Rolls Royce', color: 'Black' }
7. Invoking a Method:
We invoke the drive()
method on the car1
object, which simulates driving the car and logs a message to the console.
car1.drive(); // Output: Hi, This is My Rolls Royce car. And its color is Black
Conclusion:
Classes in JavaScript provide a cleaner and more structured way to define objects and their behavior. By leveraging classes, you can create reusable and maintainable code, making it easier to build complex applications. In this blog post, we've explored the basics of using classes in JavaScript for Object-Oriented Programming.
Stay tuned for more insights and advanced techniques in utilizing classes and OOP principles in JavaScript. Happy coding!
Top comments (0)