JavaScript uses prototype-based inheritance and does not traditionally use classes like many object-oriented languages. However, with the introduction of ES6, also known as ES2015, we're now able to declare classes in JavaScript.
The correct way to declare a class named 'Car' in JavaScript is by using the class keyword followed by the name of the class as shown in the answer class Car {}
.
A basic class declaration in JavaScript has the following syntax:
class ClassName {
// class body
}
In the case of our 'Car' class, it would be declared as:
class Car {
// class body
}
Let's assume our 'Car' class has properties like brand, model, and color. We want these properties to be customizable for every car object we create.
We can include a method in our 'Car' class, known as a constructor, to set these values while creating a new car object.
Here's what our 'Car' class would look like with a constructor:
class Car {
constructor(brand, model, color) {
this.brand = brand;
this.model = model;
this.color = color;
}
}
We can then create a new car object as follows:
let myCar = new Car('Toyota', 'Corolla', 'Blue');
When logging myCar
in the console, you would get the object:
{ brand: 'Toyota', model: 'Corolla', color: 'Blue' }
When using class declarations, here are some best practices to follow:
PascalCase
for class names. While this is not enforced by the JavaScript language, it is a widely accepted industry standard.function
keyword. Again, this is a requirement imposed by the language.this
to access properties that belong to the class.Remember, even though ES6 introduced a class
keyword, JavaScript is still a prototype-based language. Under the hood, this "class" is a syntactical sugar over JavaScript's existing prototype-based inheritance. The class syntax does not introduce a new object-oriented inheritance model to JavaScript.