본문 바로가기
2021~_Development Notes/JS Patterns

Mixin pattern

by Indie J 2024. 12. 8.

An object used to

Add reusable functionality to another object or class, without using inheritance.

Simply, adding functionalities to the target prototype!


  1. We can add the dogFunctionality mixin to the Dog prototype with the Object.assign method.
  2. We can add animalFunctionality to the dogFunctionality prototype, using Object.assign. In this case, the target object is dogFunctionality.
class Dog {
  constructor(name) {
    this.name = name;
  }
}

const animalFunctionality = {
  walk: () => console.log("Walking!"),
  sleep: () => console.log("Sleeping!")
};

const dogFunctionality = {
  __proto__: animalFunctionality,
  bark: () => console.log("Woof!"),
  wagTail: () => console.log("Wagging my tail!"),
  play: () => console.log("Playing!"),
  walk() {
    super.walk();
  },
  sleep() {
    super.sleep();
  }
};

Object.assign(Dog.prototype, dogFunctionality);

const pet1 = new Dog("Daisy");

console.log(pet1.name);
pet1.bark(); 
pet1.play(); 
pet1.walk();
pet1.sleep();

An example of a mixin is Window interface in a browser environment.

The Window object implements many of its properties from the WindowOrWorkerGlobalScope and WindowEventHandlers mixins, which allow us to have access to properties such as setTimeout and setInterval, indexedDB, and isSecureContext.

'2021~_Development Notes > JS Patterns' 카테고리의 다른 글

Observer pattern  (0) 2024.12.08
Module pattern  (0) 2024.12.08
Middleware Pattern  (0) 2024.12.08
Mediator Pattern  (0) 2024.12.08
Flyweight Pattern  (0) 2024.12.08