효율적인 객체 설계
재사용성과 효율적인 관리를 위한 객체 설계가 필요하다.
알고가야 하는 내용
- 자바스크립트에서는 상속받는 타입을 하위 타입(subtype), 상속하는 타입을 상위 타입(supertype) 이라고 부릅니다
- 생성자 함수에서의
this
는 그 생성자 함수의 인스턴스를 의미한다
1. 생성자 훔치기
call
이나 apply
를 이용하여 인스턴스를 인수로 전달하고 프로퍼티를 상속받는 방법을 생성자 훔치기라고 합니다
// 기본 소시지 레시피
function Sausage(el1, el2) {
this.inside1 = el1;
this.inside2 = el2;
}
function FireSausage(el1, el2, el3) {
Sausage.call(this, el1, el2);
this.inside3 = el3;
}
var myNewSausage = new FireSausage("돼지고기", "마늘", "불맛");
console.log(myNewSausage.inside1); // "돼지고기"
console.log(myNewSausage.inside2); // "마늘"
console.log(myNewSausage.inside3); // "불맛"
2. 프로토타입 상속
Object.create(prototype)
메소드를 사용하면 [[Prototype]]
이 참조 할 생성자의 prototype
프로퍼티를 설정하여 상위 타입의 메소드도 사용할 수 있다
constructor
를 따로 변경해주지 않으면 상위 타입의 생성자를 가지고 있다
// 기본 소시지 레시피
function Sausage(el1, el2) {
this.inside1 = el1;
this.inside2 = el2;
}
// 소시지 프로토타입 선언
Sausage.prototype.taste = function () {
return this.inside1 + "와 " + this.inside2 + " 맛이 난다!";
}
// 불맛 소시지 레시피
function FireSausage(el1, el2, el3) {
Sausage.call(this, el1, el2); // 1. 생성자 훔치기 부분
this.inside3 = el3;
}
// 프로토 타입 상속
FireSausage.prototype = Object.create(Sausage.prototype);
// FireSausage 의 생성자를 기존의 상위타입 Sausage 에서 FireSausage 로 변경
FireSausage.prototype.constructor = FireSausage;
FireSausage.prototype.flavor = function () {
return this.inside3 + "의 풍미도 있다!";
}
var myNewSausage = new FireSausage("돼지고기", "마늘", "불맛");
console.log(myNewSausage.taste()); // "돼지고기와 마늘 맛이 난다!"
console.log(myNewSausage.flavor()); // "불맛의 풍미도 있다!"
참고
'JS > JS 핵심 개념' 카테고리의 다른 글
JS hoisting (0) | 2023.03.13 |
---|---|
JS 클래스 (0) | 2023.03.13 |
JS 프로토타입 (0) | 2023.03.13 |
JS 생성자 (0) | 2023.03.13 |
JS closure 함수 (0) | 2023.03.13 |