In JavaScript, classes provide a way to create objects with similar properties and methods. They were introduced in ECMAScript 2015 (ES6) to make it easier to work with object-oriented programming paradigms. Here's an overview of how classes work in JavaScript:
Syntax:The class syntax in JavaScript:
class MyClass {
constructor(property1, property2) {
this.property1 = property1;
this.property2 = property2;
}
// Methods
method1() {
// Method logic
}
method2() {
// Method logic
}
}
Constructor Method:
The constructor()
method is a special method inside a class that gets executed when you create a new instance of that class using the new
keyword. It's used for initializing properties of the object.
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
}
Class Methods:
Methods inside a class are regular functions that can be called on instances of that class.
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
greet() {
return `Hello, my name is ${this.name} and I am ${this.age} years old.`;
}
}
let person1 = new Person("Alice", 30);
console.log(person1.greet()); // Output: Hello, my name is Alice and I am 30 years old.
Inheritance:
Classes can inherit properties and methods from other classes using the extends
keyword.
class Animal {
constructor(name) {
this.name = name;
}
makeSound() {
console.log("Some sound");
}
}
class Dog extends Animal {
constructor(name, breed) {
super(name);
this.breed = breed;
}
makeSound() {
console.log("Woof!");
}
}
let myDog = new Dog("Buddy", "Golden Retriever");
console.log(myDog.name); // Output: Buddy
myDog.makeSound(); // Output: Woof!
Static Methods:
Static methods are called on the class itself, not on instances. They are defined using the static
keyword.
class MathOperations {
static add(a, b) {
return a + b;
}
static subtract(a, b) {
return a - b;
}
}
console.log(MathOperations.add(5, 3)); // Output: 8
console.log(MathOperations.subtract(5, 3)); // Output: 2
Classes in JavaScript provide a more structured way to work with object-oriented principles and help in creating and managing objects with similar behaviors and properties.