ES6+ Features
ES6 Classes
class, constructor, extends
💡 ES6 classes ek "cleaner blueprint syntax" hain — underneath JavaScript abhi bhi prototypes use karta hai (Advanced JavaScript category mein detail), lekin class syntax C++/Java jaisa familiar, readable structure deta hai.
class keyword se class define karte hain. constructor() object banate waqt automatically chalता hai. Methods bina "function" keyword ke likhe jaate hain. extends se inheritance, super() se parent class ka constructor/methods call karte hain.
class Animal {
constructor(name) {
this.name = name;
}
speak() {
return this.name + " makes a sound.";
}
}
class Dog extends Animal {
constructor(name, breed) {
super(name); // parent constructor call karo
this.breed = breed;
}
speak() { // override
return this.name + " barks!";
}
}
const dog = new Dog("Rex", "Labrador");
console.log(dog.speak()); // "Rex barks!"
console.log(dog.name); // "Rex" — parent se inherited
class Counter {
#count = 0; // private field (# prefix, modern JS)
increment() {
this.#count++;
return this.#count;
}
}🏗️
ES6 classes ek "cleaner blueprint syntax" hain — underneath JavaScript abhi bhi prototypes use karta hai (Advanced JavaScript category mein detail), lekin class syntax C++/Java jaisa familiar, readable structure deta hai.
1 / 2
⚡ Quick Recap
- class + constructor() = blueprint + setup logic
- extends + super() = inheritance
- # prefix = true private fields (modern JS)
On this page (2 subtopics)
static keyword se class-level methods/properties banते hain — object banaye bina, seedha class naam se call hote hain. Utility functions jo class se related hain lekin instance-specific nahi, in ke liye common.
class MathHelper {
static square(x) {
return x * x;
}
static PI = 3.14159;
}
console.log(MathHelper.square(5)); // 25 — object banaye bina call
console.log(MathHelper.PI); // 3.14159Tip: Factory methods (alternative constructors) banane ke liye static methods common pattern hain — jaise static fromJSON(data) { return new MyClass(...); }.
get/set keywords se "computed properties" bana sakte ho — property jaisa access hota hai (obj.value), lekin underneath function chal raha hai, validation/computation ke liye.
class Circle {
constructor(radius) {
this.radius = radius;
}
get area() { // computed, method jaisa call nahi hota
return Math.PI * this.radius ** 2;
}
set diameter(d) { // set karne par radius update
this.radius = d / 2;
}
}
const c = new Circle(5);
console.log(c.area); // property jaisa access, () ki zaroorat nahi
c.diameter = 20; // setter chalta hai
console.log(c.radius); // 10Tip: Getters/setters se class ka "external interface" clean, property-jaisa rehta hai, jabki internally validation/computation ho sakta hai — encapsulation ka acha example.