Interview question
How do ES6 classes work and how do they compare to prototype-based inheritance? ES6 classes कैसे काम करते हैं और prototype-based inheritance से कैसे compare होते हैं?
Answer
ES6 classes are syntactic sugar over JavaScript's existing prototype-based inheritance model - they don't introduce a new inheritance mechanism, just a cleaner syntax for it.
// ES6 class syntax
class Animal {
constructor(name) {
this.name = name;
}
speak() {
return `${this.name} makes a sound`;
}
static create(name) {
return new Animal(name); // static method - called on the class, not an instance
}
}
const dog = new Animal('Dog');
console.log(dog.speak()); // Dog makes a sound
// Class inheritance with extends and super
class Dog extends Animal {
constructor(name, breed) {
super(name); // calls Animal's constructor
this.breed = breed;
}
speak() {
return `${super.speak()}, specifically a bark`; // calls parent method too
}
}
const myDog = new Dog('Rex', 'Labrador');
console.log(myDog.speak()); // Rex makes a sound, specifically a bark
console.log(myDog instanceof Animal); // true
// Equivalent using prototype-based syntax (pre-ES6)
function AnimalOld(name) {
this.name = name;
}
AnimalOld.prototype.speak = function() {
return `${this.name} makes a sound`;
};
function DogOld(name, breed) {
AnimalOld.call(this, name); // manual constructor chaining
this.breed = breed;
}
DogOld.prototype = Object.create(AnimalOld.prototype); // manual prototype chain setup
DogOld.prototype.constructor = DogOld;
// Under the hood, classes still use prototypes
console.log(typeof Animal); // 'function' - classes ARE functions
console.log(dog.__proto__ === Animal.prototype); // trueES6 classes JavaScript के existing prototype-based inheritance model पर syntactic sugar हैं - नया inheritance mechanism नहीं लाते, बस cleaner syntax देते हैं।
class Animal {
constructor(name) {
this.name = name;
}
speak() {
return `${this.name} makes a sound`;
}
static create(name) {
return new Animal(name);
}
}
const dog = new Animal('Dog');
console.log(dog.speak()); // Dog makes a sound
// extends और super से inheritance
class Dog extends Animal {
constructor(name, breed) {
super(name);
this.breed = breed;
}
speak() {
return `${super.speak()}, specifically a bark`;
}
}
const myDog = new Dog('Rex', 'Labrador');
console.log(myDog.speak());
console.log(myDog instanceof Animal); // true
// Prototype-based equivalent (ES6 से पहले)
function AnimalOld(name) {
this.name = name;
}
AnimalOld.prototype.speak = function() {
return `${this.name} makes a sound`;
};
function DogOld(name, breed) {
AnimalOld.call(this, name);
this.breed = breed;
}
DogOld.prototype = Object.create(AnimalOld.prototype);
// अंदर से classes अभी भी prototypes use करती हैं
console.log(typeof Animal); // 'function'
console.log(dog.__proto__ === Animal.prototype); // trueWas this answer clear?