In JavaScript, classes provide a way to define blueprints for creating objects with similar properties and methods. Introduced in ECMAScript 2015 (ES6), classes offer a more structured and familiar syntax for working with objects, similar to class-based languages like Java or Python. Here's an example:
// Defining a class
class Car {
constructor(make, model, year) {
this.make = make;
this.model = model;
this.year = year;
}
// Method defined inside the class
getDetails() {
return `${this.year} ${this.make} ${this.model}`;
}
}
// Creating an instance of the class (object)
let myCar = new Car('Toyota', 'Corolla', 2022);
// Using the class method
console.log(myCar.getDetails()); // Output: 2022 Toyota Corolla
Here's what's happening:
-
The class keyword is used to define a class named
Car
. It has aconstructor
method that gets called when a new object is created. This method initializes the object's properties (make, model, year
) when a newCar
object is instantiated. -
Inside the class, there's a method
getDetails()
that returns a formatted string using the object's properties. -
An instance of the Car class is created using the
new
keyword, passing in arguments for themake, model, and year
. -
The instance
myCar
has access to the properties and methods defined within theCar
class.
Classes in JavaScript are a syntactical sugar over the prototype-based inheritance system that JavaScript traditionally used. Underneath, classes are still based on prototypes. They provide a clearer and more organized way to define object blueprints and their methods.
It's important to note that while classes in JavaScript offer a more familiar syntax for developers coming from class-based languages, JavaScript remains a prototype-based language at its core. Classes provide a convenient way to work with objects but are still built on top of JavaScript's prototypal inheritance.