1 분 소요

서브 타입 & 슈퍼 타입

function Sausage(el1, el2) {
    this.inside1 = el1;
    this.inside2 = el2;
}

Sausage.prototype.taste = function() {
    return this.inside1 + "" + this.inside2 + " 맛이 난다!";
}

let mySausage = new Sausage("돼지고기", "마늘");
console.log(mySausage.taste());	// "돼지고기와 마늘 맛이 난다!"

function FlavoredSausage(el1, el2, el3) {
    this.inside1 = el1;
    this.inside2 = el2;
    this.inside3 = el3;
}

FlavoredSausage.prototype.taste = function() {
    return this.inside1 + "" + this.inside2 + " 맛이 난다!";
}

FlavoredSausage.prototype.flavor = function() {
    return this.inside3 + "의 풍미도 있다!";
}

let myFlavoredSausage = new FlavoredSausage("돼지고기", "마늘", "불맛");
console.log(myFlavoredSausage.taste());	// "돼지고기와 마늘 맛이 난다!"
console.log(myFlavoredSausage.flavor());	// "불맛의 풍미도 있다!"

1. 생성자 훔치기

function Sausage(el1, el2) {
    this.inside1 = el1;
    this.inside2 = el2;
}

Sausage.prototype.taste = function() {
    return this.inside1 + "" + this.inside2 + " 맛이 난다!";
}

let mySausage = new Sausage("돼지고기", "마늘");
console.log(mySausage.taste());	// "돼지고기와 마늘 맛이 난다!"

function FlavoredSausage(el1, el2, el3) {
    Sausage.call(this, el1, el2);
    this.inside3 = el3;
}

let myFlavoredSausage = new FlavoredSausage("돼지고기", "마늘", "불맛");
console.log(myFlavoredSausage.inside1);	// "돼지고기"
console.log(myFlavoredSausage.inside2);	// "마늘"
console.log(myFlavoredSausage.inside3);	// "불맛"

생성자는 함수이기 때문에 call() 메소드를 사용할 수 있습니다. FlavoredSausage 생성자 함수의 this는 FlavoredSausage의 인스턴스입니다. 그렇기 때문에 Sausage.call 의 this는 바로 FlavoredSausage의 인스턴스를 가르키게 됩니다.

이렇게 call이나 apply를 이용하여 인스턴스를 인수로 전달하고 프로퍼티를 상속받는 방법을 생성자 훔치기(constructor stealing)이라고 표현합니다.

이렇게 프로퍼티를 상속 받는 타입을 하위 타입(subtype), 상속을 해주는 타입을 상위 타입(supertype)이라고 합니다.

2. 프로토타입 상속

function Sausage(el1, el2) {
    this.inside1 = el1;
    this.inside2 = el2;
}

Sausage.prototype.taste = function() {
    return this.inside1 + "" + this.inside2 + " 맛이 난다!";
}

let mySausage = new Sausage("돼지고기", "마늘");
console.log(mySausage.taste());	// "돼지고기와 마늘 맛이 난다!"

function FlavoredSausage(el1, el2, el3) {
    Sausage.call(this, el1, el2);
    this.inside3 = el3;
}

FlavoredSausage.prototype = Object.create(Sausage.prototype);
FlavoredSausage.prototype.constructor = FlavoredSausage;	// 이 줄이 없다면 myFlavoredSausage의 [[Prototype]] 안 constructor가 없다

FlavoredSausage.prototype.flavor = function() {
    return this.inside3 + "의 풍미도 있다!";
}

let myFlavoredSausage = new FlavoredSausage("돼지고기", "마늘", "불맛");
console.log(myFlavoredSausage.taste());	// "돼지고기와 마늘 맛이 난다!"
console.log(myFlavoredSausage.flavor());	// "불맛의 풍미도 있다!"

Object.create() 메소드는 [[Prototype]]이 참조할 생성자의 prototype 프로퍼티를 설정합니다. 이제 프로토타입 체인을 통해 상위 타입의 메소드도 사용할 수 있게 되었습니다. 이때 인스턴스의 constructor를 FlavoredSausage로 설정해야 한다는 것에 주의하세요.

댓글남기기