কম্পিউটার টিউটোরিয়াল

JavaScript-এ প্রোটোটাইপ মেথড দিয়ে কনস্ট্রাক্টর ভেরিয়েবল অ্যাক্সেস করা

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

চলানোর পদ্ধতি

  1. কোডটি prototypeDemo.js নামে সংরক্ষণ করুন।
  2. টার্মিনালে চালান: 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); // সঠিক ইনস্ট্যান্স
};
  1. জাভাস্ক্রিপ্ট call() মেথড আর্গুমেন্টসহ ব্যাখ্যা

  2. জাভাস্ক্রিপ্টে Array.prototype.includes() মেথড

  3. জাভাস্ক্রিপ্ট দিয়ে পেরেন্ট এলিমেন্ট অ্যাক্সেস করা

  4. জাভাস্ক্রিপ্টে ফাংশন রিটার্ন করা অ্যারে অ্যাক্সেস করা