[JavaScript] 프로토타입 체인, extends와 super

앞서 적은 객체지향의 개념 포스트에서 상속의 개념은 부모의 공통된 프로퍼티(속성)와 메서드를 상속받을 수 있고, 자식의 개별 프로퍼티와 메서드를 추가할 수 있는 것이라 했다. 프로토타입 체인이란 이러한 상속 관계에서 자식 요소를 이용해 메서드를 사용하려 할 때, 그것이 자식이 가지고 있는 메서드가 아닐 때 그 메서드를 부모 class의 프로토타입에서 찾는 것을 말한다. 

 

예시:

let arr = [1];

arr.push(2);
console.log(arr) //[1,2]

//이 상황에서 우리가 arr에 push()기능을 추가하지 않았음에도 push()를 사용할 수 있는건
//프로토타입 체인을 이용해 
//arr의 부모 class인 Array의 prototype에서 push()를 찾아왔기 때문이다.
//콘솔에 Array.prototype을 찍어 push() 존재 여부 확인 가능.

 

자식 class 가 부모 class의 프로토타입을 상속받으면서 자식만의 개별 기능을 갖도록 하기 위해서 super()를 사용할 수 있다.

 

super 뒤에 ()가 붙으면 super는 부모class의 생성자를 호출할 수 있게 된다.

super 뒤에 .을 붙이면 부모 class의 메서드를 호출 할 수 있다. 

 

예시:

class Animal {
    constructor(name, population, area){
        this.명칭= name;
        this.개체수= population;
        this.우리= area;
    }
    noFood(){
        return `${this.명칭}에게 먹이를 주지 마시오.`;
    }
}

class Zoo extends Animal{  //extends를 사용해 Zoo가 Animal을 상속받게끔 할 수 있다
	constructor(name, population, area, food){  //food 추가
        super(name, population, area);  //super()를 사용해 Animal의 constructor 상속
        this.먹이 = food;   //Zoo 고유의 기능 '먹이' 추가
    }
    noFood(){
        //super. 사용해 Animal의 메서드 사용
    	return super.noFood()+` 하지만 ${this.먹이}은(는) 가능합니다.`
    }
}

let 토끼 = new Zoo('토끼', 10, 'A','당근');
let 기린 = new Animal('기린', 5, 'C');
...

console.log(토끼.noFood()); //토끼에게 먹이를 주지 마시오. 하지만 당근은(는) 가능합니다.
console.log(기린.noFood()); //기린에게 먹이를 주지 마시오

 

 

부모는 __proto__를 이용해 찾을 수 있다. 모든 class의 최고 조상은 Object.

 

예시:

let div = document.createElement('div');

div.__proto__ 
div.__proto__.__proto__
div.__proto__.__proto__.__proto__
div.__proto__.__proto__.__proto__.__proto__
div.__proto__.__proto__.__proto__.__proto__.__proto__
div.__proto__.__proto__.__proto__.__proto__.__proto__.__proto__
div.__proto__.__proto__.__proto__.__proto__.__proto__.__proto__.__proto__

 

 


이 글은 코드스테이츠 블로깅 과제로, 배운 것을 요점정리한 글입니다.

 

참고자료