β What is a Class?
A class is a blueprint for creating objects. It bundles data (properties) and actions (methods) into one convenient structure.
π Basic Class Syntax
jsCopyEditclass Person {
constructor(name, age) {
this.name = name; // Property
this.age = age; // Property
}
greet() { // Method
console.log(`Hello! My name is ${this.name} and I am ${this.age} years old.`);
}
}
const person1 = new Person("Alice", 25); // Create new object
person1.greet(); // Hello! My name is Alice and I am 25 years old.
π Key Points
class
keyword declares a class.constructor()
is a special method to initialize new objects.- Methods inside the class define behaviors.
- Use
new
keyword to create instances (objects) of the class.
π Why Use Classes?
- Cleaner syntax for creating objects.
- Makes object-oriented programming (OOP) easier.
- Supports inheritance and reuse of code.
- Helps organize code in bigger projects.
π§ͺ Try it Yourself!
jsCopyEditclass Animal {
constructor(type) {
this.type = type;
}
speak() {
console.log(`This is a ${this.type}`);
}
}
const dog = new Animal("dog");
dog.speak(); // This is a dog
π§ Summary
Term | Meaning |
---|---|
Class | Blueprint to create objects |
Constructor | Initializes new objectβs data |
Method | Function inside a class |
Instance | An object created from a class |
new keyword | Creates an instance of a class |