Skip to main content
InterviewHubPRO
Section Overview
Q356

Question 356 of 536

Part 6: Async Internals, Memory, Microtasks & Web APIs (329 - 403)

66%
JavaScript & V8 Internals (536 Qs)•Part 6: Async Internals, Memory, Microtasks & Web APIs (329 - 403)

Mixin Example using Object composition

senior LevelCode ExampleAsync & PromisesEvent LoopHTTP & REST APIs

Mixins in JavaScript allow objects to borrow methods from multiple source objects without using rigid class inheritance hierarchies. By utilizing Object.assign() or object composition, behaviors can be mixed into target prototypes dynamically.

javascript
  // Define a mixin
  const canEat = {
    eat() {
      console.log("Eating...");
    }
  };

  const canWalk = {
    walk() {
      console.log("Walking...");
    }
  };

  const canRead = {
    read() {
      console.log("Reading...");
    }
  };

  // Create a class
  class Person {
    constructor(name) {
      this.name = name;
    }
  }

  // Apply mixins
  Object.assign(Person.prototype, canEat, canWalk, canRead);

  // Use it
  const person = new Person("Alex");
  person.eat();  // Output: Eating...
  person.walk(); // Output: Walking...
  person.read(); // Output: Reading...