In JavaScript, classes are a special type of function introduced in ECMAScript 6 (ES6) that provide a more structured and object-oriented approach to creating objects. Classes can be defined similarly to function declarations and function expressions. They offer a clear and concise syntax for creating objects and managing inheritance.
Classes are executed in strict mode, which helps catch common coding errors and enforce a more disciplined coding style. This strict mode eliminates some of the silent errors that can occur in non-strict mode.
JavaScript class syntax primarily consists of two components:
1. Class declarations
2. Class expressions
Class declarations are used to define a class with a specific name and a body that contains the methods and constructors. Here's the syntax for a class declaration:
// Class Declaration
class Person {
// Constructor method
constructor(name, age) {
this.name = name;
this.age = age;
}
// Method
greet() {
console.log(`Hello, my name is ${this.name} and I am ${this.age} years old.`);
}
}
// Creating an instance of the class
const person1 = new Person('John', 30);
person1.greet(); // Output: Hello, my name is John and I am 30 years old.
Class expressions are used to create classes that are assigned to variables. They can be named or unnamed, and are useful when defining classes dynamically or within other expressions.
// Named Class Expression
const Animal = class Animal {
constructor(name) {
this.name = name;
}
speak() {
console.log(`${this.name} makes a noise.`);
}
};
// Creating an instance of the class
const animal1 = new Animal('Dog');
animal1.speak(); // Output: Dog makes a noise.
// Unnamed Class Expression
const Car = class {
constructor(make, model) {
this.make = make;
this.model = model;
}
displayInfo() {
console.log(`Car: ${this.make} ${this.model}`);
}
};
// Creating an instance of the class
const car1 = new Car('Toyota', 'Corolla');
car1.displayInfo(); // Output: Car: Toyota Corolla
• Class Declarations: Define a class with a specific name and a body.
• Class Expressions: Define a class and assign it to a variable, which can be named or unnamed.
• Strict Mode: Classes are executed in strict mode, catching errors that might be silent in non-strict mode.
• Constructor Method: Used to initialize new instances of the class.
• Methods: Functions defined within a class that define the behavior of the objects created from the class.