this · super · extends · new
this
— references the current instance or call‑site receiver.extends
— creates a subclass that inherits from a base class.super
— calls the base constructor or methods from a subclass.new
— creates an instance by running the constructor and wiring the prototype.
Syntax
// Class with this/new
class User {
constructor(name) {
this.name = name; // use 'this'
}
hello() { console.log("Hi", this.name); }
}
// Inheritance with extends/super
class Admin extends User {
constructor(name, level) {
super(name); // must call first
this.level = level;
}
hello() {
super.hello(); // call base method
console.log("Level:", this.level);
}
}
const u = new User("Mamun"); // 'new'
u.hello();
Examples
// ১) এটি (this) — মেথড বনাম অ্যারো
শ্রেণী বোতাম {
constructor(লেবেল) { এটি.লেবেল = লেবেল; }
চাপ() { কনসোল.লগ("চাপ:", এটি.লেবেল); } // মেথড: ডায়নামিক this
// অ্যারো‑ফিল্ড: this লেক্সিক্যালি ক্যাপচার হয়
ক্রিয়া = () => কনসোল.লগ("ক্রিয়া:", এটি.লেবেল);
}
const b = নতুন বোতাম("Save");
const প্রেস = b.চাপ;
প্রেস.call({ লেবেল: "Hack" }); // "চাপ: Hack" — কলসাইট নির্ভর
b.ক্রিয়া.call({ লেবেল: "Hack" }); // "ক্রিয়া: Save" — অ্যারো this স্থির
// ২) প্রসারিত/অভিভাবক — ওভাররাইড ও super.method
শ্রেণী লগার {
log(msg) { কনসোল.লগ("[LOG]", msg); }
}
শ্রেণী ফাইললগার প্রসারিত লগার {
log(msg) {
অভিভাবক.log(msg); // বেস আচরণ
কনসোল.তথ্য("ফাইলে লেখা:", msg);
}
}
// ৩) নতুন (new) — ছাড়া কল করলে সমস্যা
শ্রেণী কাউন্ট {
constructor(n = 0) { এটি.n = n; }
}
চেষ্টা {
const x = কাউন্ট(5); // ❌ নতুন ছাড়া — TypeError
} ধরুন (ত্রু) {
কনসোল.সতর্ক("নতুন লাগবে:", ত্রু.message);
}
const y = নতুন কাউন্ট(5); // ✅
কনসোল.লগ("y.n =", y.n);
Notes
- In subclass constructors, call
super(...)
before usingthis
. super.method()
calls the base prototype method; inside static methods,super
refers to the base constructor (useful forsuper.someStatic()
).- Arrow fields capture
this
lexically; prefer normal methods when you need prototype sharing orsuper
. new
creates an object linked to the constructor’s prototype, runs the constructor, and returns the object (unless the constructor returns another object).- Avoid rebinding methods when possible; prefer class fields with arrows only for event handlers that need fixed
this
. - Keep one language style per file for readability.