Show List

Classes

In JavaScript, classes provide a way to define blueprints for creating objects with similar properties and methods. Here's an explanation of various features related to classes, along with code examples:

Classes:

Classes are a template for creating objects with methods and properties. They are declared using the class keyword.


class Person { constructor(name, age) { this.name = name; this.age = age; } greet() { console.log(`Hello, my name is ${this.name} and I am ${this.age} years old.`); } } const person1 = new Person('Alice', 30); person1.greet(); // Output: Hello, my name is Alice and I am 30 years old.

Getters and Setters:

Getters and setters allow you to define computed properties or perform validation on property assignment.


class Rectangle { constructor(width, height) { this._width = width; this._height = height; } get area() { return this._width * this._height; } set width(value) { if (value > 0) { this._width = value; } else { console.error('Width must be a positive number'); } } get width() { return this._width; } } const rect = new Rectangle(5, 10); console.log(rect.area); // Output: 50 rect.width = 20; console.log(rect.width); // Output: 20

Class Expressions:

A class expression is another way to define a class. It can be named or unnamed.


const MyClass = class { constructor(name) { this.name = name; } greet() { console.log(`Hello, ${this.name}!`); } }; const obj = new MyClass('World'); obj.greet(); // Output: Hello, World!

Static Methods and Properties:

Static methods and properties are associated with the class itself, rather than instances of the class.


class MathUtils { static square(x) { return x * x; } } console.log(MathUtils.square(5)); // Output: 25

Inheritance:

Classes can inherit properties and methods from other classes using the extends keyword.


class Animal { constructor(name) { this.name = name; } speak() { console.log(`${this.name} makes a sound.`); } } class Dog extends Animal { constructor(name) { super(name); // Call the constructor of the parent class } speak() { console.log(`${this.name} barks.`); } } const dog = new Dog('Buddy'); dog.speak(); // Output: Buddy barks.

In this example, Dog inherits from Animal. The speak method is overridden in Dog, but it still calls the speak method of Animal using super.speak(). This is how inheritance and method overriding work in JavaScript classes.



Next: Promises


    Leave a Comment


  • captcha text