Study/JavaScript

[JavaScript_study] Mixin

갈푸라떼 2022. 4. 14. 17:25

* Mixin

오브젝트는 단 하나의 prototype을 가리킬 수 있다 (부모는 단 하나!)
하지만! 여러개의 함수들을 상속하고 싶다!

Mixin을 이용해서 여러개의 객체를 재사용할때 유용하게 사용할 수 있다.

 

* Mixin 예시 코드

const play = {
  play: function () {
    console.log(`${this.name} 놀아요!`);
  },
};

const sleep = {
  sleep: function () {
    console.log(`${this.name} 자요!`);
  },
};

function Dog(name) {
  this.name = name;
}

// assign을 이용해서 Mixin해준다.
Object.assign(Dog.prototype, play, sleep);
const dog = new Dog('멍멍');
console.log(dog);

// Mixin을 해주었기 때문에 play, sleep함수 둘다 사용이 된다.
dog.play();
dog.sleep();

// class에서도 활용이 가능하다.
// 자바스크립트 class는 class처럼 보이지만 실제로는 prototype를 베이스로 하고 있다.
// Animal을 이미 상속 받고 있어도 assign을 이용해서 다른 함수를 상속 받을 수 있다.
class Animal {}
class Tiger extends Animal {
  constructor(name) {
    super();
    this.name = name;
  }
}

// Class인 Tiger에 prototype을 베이스로 해서 Mixin을 사용할 수 있다.
Object.assign(Tiger.prototype, play, sleep);
const tiger = new Tiger('어흥!');
tiger.play();
tiger.sleep();