Classes are templates for creating objects with shared properties and methods.
Example:
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
greet() {
console.log('Hello, my name is ${this.name}!');
}
}
let person1 = new Person("Alice", 25);
person1.greet(); // Output: Hello, my name is Alice!
Class Constructor:
The constructor initializes object properties when an instance of a class is created.
Example:
class Rectangle {
constructor(width, height) {
this.width = width;
this.height = height;
}
}
let rect = new Rectangle(10, 5);
console.log(rect.width); // Output: 10
Class Methods:
Class methods are functions defined within a class, providing behavior to instances of the class.
Example:
class Circle {
constructor(radius) {
this.radius = radius;
}
calculateArea() {
return Math.PI * this.radius 2;
}
}
let circle1 = new Circle(3);
console.log(circle1.calculateArea()); // Output: 28.274333882308138
Static Methods:
Static methods belong to the class itself, not its instances, often used for utility functions.
Example:
class MathUtils {
static multiply(a, b) {
return a * b;
}
}
console.log(MathUtils.multiply(5, 3)); // Output: 15
Extends:
The 'extends' keyword allows a child class to inherit properties and methods from a parent class.
Example:
class Animal {
constructor(name) {
this.name = name;
}
speak() {
console.log('${this.name} makes a sound.');
}
}
class Dog extends Animal {
speak() {
console.log('${this.name} barks.');
}
}
let dog1 = new Dog("Buddy");
dog1.speak(); // Output: Buddy barks.