__proto__
속성으로 객체 인스턴스에 구현하고있음 class Human {
constructor(name, age) {
this.name = name;
this.age = age;
}
sleep() {
console.log(`${this.name}은 잠에 들었습니다`);
}
}
let kimcoding = new Human('김코딩', 30);
// 실습해보세요
Human.prototype.constructor === Human;
Human.prototype === kimcoding.__proto__;
Human.prototype.sleep === kimcoding.sleep; //다 true 나옴
상속을 js에서 구현할때 사용, 예를들어 Student, Human클래스가 존재한다 가정, 메서드와 속성을 객체로 구현해보자.
let kimcoding = new Human('김코딩', 30);
// 속성
kimcoding.age;
kimcoding.gender;
// 메서드
kimcoding.eat();
kimcoding.sleep();
학생은 학생이기 이전에 사람이므로 Student는 Human메소드를 상속받을 수 있음
let parkhacker = new Student('박해커', 22);
// 속성
parkhacker.grade;
// 메서드
parkhacker.learn();
Student는 Human의 특징을 그대로 물려받음. 속성과 메서드를 물려받는 클래스를 자식클래스, 이 과정을 상속이라고 함
브라우저에서 DOM을 사용하면 document.createElement('div')로 새로운 엘리먼트를 만들수 있다. 이렇게 생성된 div 엘리먼트는 HTMLDivElement라는 클래스의 인스턴스이다. 그거의 부모는 HTMLElement > Element > Node > EventTarget > Object (모든 클래스의 조상)
인스턴스의 __proto__
를 이용하면 부모 클리스의 프로토타입 혹은 부모의 부모클래스의 프로토타입을 탐색할 수 있음
let div = document.createElement('div');
div.__proto__ //HTMLDivElement
div.__proto__.__proto__ //HTMLElement
div.__proto__.__proto__.__proto__ //Element
꿀벌은 발달단계를 거치며 성장한다. 각 단계마다 특징이 있는데 다양한 class가 있다. 이를통해 상속을 학습합니다.
Grub
ㄴBee
ㄴㄴHoneyMakerBee
ㄴㄴForagerBee
class Grub {
constructor(age,color,food,eat){ //속성
this.age = 0;
this.color = 'pink';
this.food = 'jelly';
}
eat(){
return `Mmmmmmmmm ${this.food}`; //메서드
}
}
class Bee extends Grub{ //상속하는 부모를 지정해준다
constructor(age,color,food,eat,job){
super(food,eat); //부모에게 받을 속성,메소드를 먼저 적고 쓴다. 사실 super();만 써도 Grub의 것들을 쓸수있다.
this.age = 5; //Grub의 age = 0 이다. Bee에 맞게 재할당했다.
this.color = 'yellow';
this.job = 'Keep on growing';
}
}
class HoneyMakerBee extends Bee{
constructor(){
super(); //이렇게 아무것도 안넣는게 정석. extend와 super만으로 된다.
this.age = 10;
this.job = 'make honey';
this.honeyPot = 0;
}
makeHoney(){
return this.honeyPot++;
}
giveHoney(){
return this.honeyPot--;
}
}