Js Classes in JavaScript
? JavaScript Classes
What is a Class?
Introduced in ES6, a class is a blueprint for creating objects with properties and methods.
Syntactic sugar over JavaScript's prototype-based inheritance.
Makes OOP (Object-Oriented Programming) style easier and cleaner.
Basic Class Syntax
class Person { constructor(name, age) { this.name = name; this.age = age; } greet() { console.log(`Hello, my name is ${this.name}, and I'm ${this.age} years old.`); }}const person1 = new Person("Alice", 30);person1.greet(); // Hello, my name is Alice, and I'm 30 years old.Key Concepts
constructor: Special method called when creating an instance.
methods: Functions inside classes.
this: Refers to the instance object.
Inheritance
class Employee extends Person { constructor(name, age, position) { super(name, age); // Call parent constructor this.position = position; } work() { console.log(`${this.name} is working as a ${this.position}.`); }}const emp = new Employee("Bob", 28, "Developer");emp.greet(); // From Personemp.work();Static Methods
Belong to the class, not instances.
Called directly on the class.
class MathUtil { static square(x) { return x * x; }}console.log(MathUtil.square(5)); // 25Summary
Classes encapsulate data and behavior.
Support inheritance for code reuse.
Static members belong to the class itself.
Want examples on private fields, getters/setters, or how classes work under the hood?