আগের Classes and OOP lesson class keyword ব্যবহার করেছে — কিন্তু এর নিচে, JavaScript object অন্য ভাষার মতো class ব্যবহার করে না। এগুলো prototype ব্যবহার করে, আর class আসলে সেই পুরনো system-এর উপর তৈরি একটি বন্ধুত্বপূর্ণ সিনট্যাক্স।
একটি object-এর prototype আরেকটি object যেখানে এটি স্বয়ংক্রিয়ভাবে property আর method খোঁজে, যখন এর নিজের একটা নেই।
const animal = {
eats: true,
}
const rabbit = Object.create(animal) // rabbit-এর prototype animal
rabbit.jumps = true
console.log(rabbit.jumps) // true — rabbit-এর নিজের property
console.log(rabbit.eats) // true — animal-এ পাওয়া গেছে, এর prototypeএকটি property prototype-এও না পাওয়া গেলে, JavaScript prototype-এর নিজের prototype-এ খুঁজতে থাকে, এভাবে, null-এ পৌঁছানো পর্যন্ত — এই chain-এর কারণেই একে prototypal inheritance বলা হয়।
function Dog(name) {
this.name = name
}
Dog.prototype.bark = function () {
console.log(`${this.name} says woof!`)
}
const rex = new Dog('Rex')
rex.bark() // "Rex says woof!" — Dog.prototype-এ পাওয়া গেছে, rex নিজে নাএকটি class method ঠিক একইভাবে prototype-এ সংরক্ষিত হয় — class prototype system replace করে না, এটা এতে লেখার একটি বেশি readable উপায়।
class Dog {
constructor(name) {
this.name = name
}
bark() {
console.log(`${this.name} says woof!`)
}
}
// পেছনে, bark() থাকে Dog.prototype-এ — আগের মতোই
console.log(typeof Dog.prototype.bark) // "function"কেন method প্রতিটি object-এ না, prototype-এ থাকে
একটি class বা constructor function থেকে তৈরি প্রতিটি object prototype-এর প্রতিটি method-এর একটা কপি শেয়ার করে — এই কারণেই method (constructor-এ সেট করা property-র মতো না) প্রতি object-এ অতিরিক্ত memory নেয় না।