Subjects

All subjects Django Java Python React Spring Boot JavaScript PHP
Sign Up Free
Question 7 of 10 · Prototypes and Inheritance
Interview question

How does JavaScript handle multiple inheritance or shared behavior across unrelated classes? JavaScript multiple inheritance या unrelated classes में shared behavior को कैसे handle करता है?

Answer

JavaScript's prototype chain only supports single inheritance (one prototype per object), but mixins provide a pattern to share behavior across multiple unrelated classes.

// Mixin pattern - objects with reusable methods
const swimMixin = {
    swim() {
        return `${this.name} is swimming`;
    }
};

const flyMixin = {
    fly() {
        return `${this.name} is flying`;
    }
};

class Duck {
    constructor(name) {
        this.name = name;
    }
}

// Apply mixins by copying methods onto the prototype
Object.assign(Duck.prototype, swimMixin, flyMixin);

const donald = new Duck('Donald');
console.log(donald.swim()); // Donald is swimming
console.log(donald.fly());  // Donald is flying

// Function-based mixins - more flexible, can be composed
const Serializable = Base => class extends Base {
    toJSON() {
        return JSON.stringify(this);
    }
};

const Comparable = Base => class extends Base {
    equals(other) {
        return JSON.stringify(this) === JSON.stringify(other);
    }
};

class Point {
    constructor(x, y) {
        this.x = x;
        this.y = y;
    }
}

// Compose multiple mixins by wrapping the base class
class EnhancedPoint extends Comparable(Serializable(Point)) {}

const p1 = new EnhancedPoint(1, 2);
console.log(p1.toJSON()); // {"x":1,"y":2}

const p2 = new EnhancedPoint(1, 2);
console.log(p1.equals(p2)); // true

// Note: classes can only 'extends' ONE parent class directly
// class Foo extends A, B {} // SYNTAX ERROR - not allowed

JavaScript का prototype chain सिर्फ single inheritance support करता है, पर mixins pattern से unrelated classes के बीच behavior share किया जा सकता है।

const swimMixin = {
    swim() {
        return `${this.name} is swimming`;
    }
};

const flyMixin = {
    fly() {
        return `${this.name} is flying`;
    }
};

class Duck {
    constructor(name) {
        this.name = name;
    }
}

// Object.assign से mixins apply करना
Object.assign(Duck.prototype, swimMixin, flyMixin);

const donald = new Duck('Donald');
console.log(donald.swim()); // Donald is swimming
console.log(donald.fly());  // Donald is flying

// Function-based mixins - ज़्यादा flexible
const Serializable = Base => class extends Base {
    toJSON() {
        return JSON.stringify(this);
    }
};

class Point {
    constructor(x, y) {
        this.x = x;
        this.y = y;
    }
}

class EnhancedPoint extends Serializable(Point) {}

const p1 = new EnhancedPoint(1, 2);
console.log(p1.toJSON()); // {"x":1,"y":2}

// Note: class सिर्फ एक parent class 'extends' कर सकती है
// class Foo extends A, B {} // SYNTAX ERROR

Was this answer clear?