Class Intro in JavaScript
? Introduction to Classes in JavaScript
What is a Class?
A class in JavaScript is a blueprint for creating objects with properties and methods. It helps you organize and reuse code more easily.
Why Use Classes?
Encapsulate data (properties) and behavior (methods)
Create multiple objects from the same template
Support inheritance and code reuse
Make object-oriented programming easier and cleaner
Basic Syntax
class Person { constructor(name, age) { this.name = name; // property this.age = age; // property } greet() { // method console.log(`Hello, my name is ${this.name} and I'm ${this.age} years old.`); }}const person1 = new Person("Alice", 30);person1.greet(); // Output: Hello, my name is Alice and I'm 30 years old.Key Points
| Feature | Description |
|---|---|
class keyword | Defines a class |
constructor | Special method to initialize new objects |
this keyword | Refers to the current object |
| Methods | Functions inside the class |
new keyword | Creates an instance (object) of the class |
How It Works
classdeclares the blueprintconstructorsets up properties for each new objectMethods are shared among all instances of the class
Use
newto create a new object from the class
Simple Example
class Car { constructor(brand) { this.brand = brand; } drive() { console.log(`${this.brand} is driving.`); }}const car1 = new Car("Toyota");car1.drive(); // Output: Toyota is driving.Would you like to learn about class inheritance, static methods, or getter/setter in classes?