An object used to
Add reusable functionality to another object or class, without using inheritance.
Simply, adding functionalities to the target prototype!
- We can add the
dogFunctionality
mixin to theDog
prototype with theObject.assign
method. - We can add
animalFunctionality
to thedogFunctionality
prototype, usingObject.assign
. In this case, the target object isdogFunctionality
.
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 |