JavaScript-এ প্রোটোটাইপ-ভিত্তিক ইনহেরিটেন্স ব্যবহার করে কনস্ট্রাক্টর ফাংশনের প্রপার্টি অ্যাক্সেস ও মডিফাই করা যায়। this কীওয়ার্ড কনটেক্সট বাঁধার কী।
কোড উদাহরণ
function Customer(fullName) {
this.fullName = fullName; // ইনস্ট্যান্স প্রপার্টি
}
// প্রোটোটাইপ মেথড যোগ
Customer.prototype.setFullName = function(newName) {
this.fullName = newName; // this = ইনস্ট্যান্স
};
var customer = new Customer("John Smith");
console.log("সিম্পল মেথড: " + customer.fullName); // John Smith
customer.setFullName("David Miller");
console.log("প্রোটোটাইপ মেথড: " + customer.fullName); // David Miller
চলানোর পদ্ধতি
- কোডটি
prototypeDemo.jsনামে সংরক্ষণ করুন। - টার্মিনালে চালান:
node prototypeDemo.js
আউটপুট
সিম্পল মেথড: John Smith
প্রোটোটাইপ মেথড: David Miller
প্রোটোটাইপ চেইন ব্যাখ্যা
customer.__proto__ === Customer.prototype // true
Customer.prototype.__proto__ === Object.prototype // true
মেমরি ইফিশিয়েন্সি
- প্রোটোটাইপ মেথড শেয়ার করা হয় (প্রতিটি ইনস্ট্যান্সের আলাদা কপি নয়)।
- কনস্ট্রাক্টরে মেথড ডিক্লেয়ার করলে প্রতিটি ইনস্ট্যান্সের আলাদা কপি বने।
ES6 Class সিনট্যাক্স (সugar coating)
class Customer {
constructor(fullName) {
this.fullName = fullName;
}
setFullName(newName) {
this.fullName = newName;
}
getFullName() {
return this.fullName;
}
}
const cust = new Customer("John Smith");
cust.setFullName("David Miller");
console.log(cust.getFullName()); // David Miller
Arrow Function সতর্কতা
// ❌ ভুল - arrow function this বাঁধে না
Customer.prototype.badMethod = () => {
console.log(this.fullName); // undefined বা window
};
// ✅ সঠিক - regular function
Customer.prototype.goodMethod = function() {
console.log(this.fullName); // সঠিক ইনস্ট্যান্স
};