Mixin
- Mixin: 상속 없이 객체나 클래스에 재사용 가능한 기능을 추가할 수 있는 객체
- 단독으로는 사용 불가
- Object.assign()을 이용하여 믹스인 (추가) 기능을 프로토타입에 추가 가능
- 믹스인 자체는 상속 가능
- Window 객체는 WindowOrWorkerGlobalScope와 WindowEventHandler의 믹스인으로 구성되어 있어서
setTimeout, setInterval, indexedDB, isSecureContext와 같은 프로퍼티 사용 가능
- 믹스인 자체를 직접적으로 사용 불가
- ES6 문법 이전 믹스인은 React에서 컴포넌트에 기능을 추가하기 위해 종송 사용했었음
하지만 믹스인이 복잡도를 증가시키고 재사용하기 어렵게 만든다고 해서
지금은 훅에 의해 대체 가능하지만 고차 컴포넌트 사용 권장함
- 객체의 프로토타입을 직접 수정하는 것은 의도하지 않은 프로토타입의 프로퍼티 수정으로 이어질 수 있어 주의가 필요
- 예시
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();
window.indexedDB.open("toDoList");
window.addEventListener("beforeunload", event => {
event.preventDefault();
event.returnValue = "";
});
window.onbeforeunload = function() {
console.log("Unloading!");
};
console.log(
"From WindowEventHandlers mixin: onbeforeunload",
window.onbeforeunload
);
console.log(
"From WindowOrWorkerGlobalScope mixin: isSecureContext",
window.isSecureContext
);
console.log(
"WindowEventHandlers itself is undefined",
window.WindowEventHandlers
);
console.log(
"WindowOrWorkerGlobalScope itself is undefined",
window.WindowOrWorkerGlobalScope
);
- 활용
반응형
'Personal-Study > UI Component Patterns' 카테고리의 다른 글
[UI Component] Design Patterns - Render Props (0) | 2023.11.06 |
---|---|
[UI Component] Design Patterns - HOC (0) | 2023.11.03 |
[UI Component] Design Patterns - Module (0) | 2023.10.31 |
[UI Component] Design Patterns - Container/Presentational (0) | 2023.10.24 |
[UI Component] Design Patterns - Provider (2) | 2023.10.24 |
댓글