자바스크립트 생성자와 프로토타입 체인을 이용한 다중 상속 방법

자바스크립트는 기본적으로 단일 상속을 지원하지만, 생성자와 프로토타입 체인을 활용하여 다중 상속을 구현할 수 있습니다. 다중 상속은 여러 개의 부모 객체로부터 속성과 메서드를 상속받는 기능을 의미합니다. 이를 통해 코드 재사용성을 높이고 객체 간의 관계를 유연하게 구성할 수 있습니다.

생성자를 활용한 다중 상속

다중 상속을 구현하기 위해 생성자를 활용하는 방법은 다음과 같습니다:

function Parent1() {
  this.name = "Parent 1";
}

function Parent2() {
  this.age = 30;
}

function Child() {
  Parent1.call(this);
  Parent2.call(this);
}

var child = new Child();
console.log(child.name); // "Parent 1"
console.log(child.age); // 30

위 코드에서 Child 생성자는 Parent1Parent2의 생성자를 call 메서드를 통해 호출하고, 현재 객체(this)에 속성을 추가하는 방식으로 다중 상속을 구현하고 있습니다. 이렇게 하면 Child 객체는 Parent1Parent2의 속성과 메서드를 모두 상속받을 수 있습니다.

프로토타입 체인을 활용한 다중 상속

프로토타입 체인을 활용하여 다중 상속을 구현하는 방법은 다음과 같습니다:

function Parent1() {
  this.name = "Parent 1";
}

Parent1.prototype.sayHello = function() {
  console.log("Hello from Parent 1");
};

function Parent2() {
  this.age = 30;
}

Parent2.prototype.sayHello = function() {
  console.log("Hello from Parent 2");
};

function Child() {}

Child.prototype = Object.create(Parent1.prototype);
Object.assign(Child.prototype, Parent2.prototype);
Child.prototype.constructor = Child;

var child = new Child();
console.log(child.name); // "Parent 1"
console.log(child.age); // 30
child.sayHello(); // "Hello from Parent 1"

위 코드에서 Child 프로토타입은 Parent1Parent2 프로토타입을 상속받도록 설정되어 있습니다. Object.create 메서드를 사용하여 Child.prototype의 프로토타입을 Parent1.prototype으로 설정한 후, Object.assign 메서드를 사용하여 Parent2.prototype의 속성을 Child.prototype에 병합합니다. 마지막으로, Child.prototype.constructorChild로 설정합니다.

이렇게 하면 Child 객체는 Parent1Parent2의 속성과 메서드를 프로토타입 체인을 통해 모두 상속받을 수 있습니다. Child 객체는 Parent2sayHello 메서드를 호출하더라도, 프로토타입 체인의 상위에서 먼저 발견되는 Parent1sayHello 메서드가 호출됩니다.

#다중상속 #자바스크립트