[JavaScript 프로토타입 체인 OOP 상속 ] extends, super , Object.create()

young·2022년 5월 26일
0

5/25~6/22 Section 2 TIL

목록 보기
5/27

❗️주의 : 공부 중인 사람의 글입니다.



Before Learn...

  • 자바스크립트는 프로토타입 기반 언어이다.

  • 자바스크립트에서 OOP 상속을 구현할 때 프로토타입 체인을 사용한다.

  • 클래스 메서드 정의와 호출하는 과정을 보며
    인스턴스객체.__proto__ === 클래스.prototype 라는 사실을 알 수 있었다.

  • 자바스크립트에서 부모 클래스를 상속받을 때 extends 키워드를 사용한다.
    
    
    




✅ TIL

  • OOP 상속 (프로토타입 체인)
  • extends, super
  • Object.create()
  • DOM의 프로토타입
    
    
    

💡 프로토타입 체인을 통한 상속 구현하기

1. 부모 class 생성



  • 클래스 Drink를 생성한다
    : class 클래스명 {...}
    
  • 메서드는 프로토타입에 저장된다
    : Drink.prototype.coffee()
class Drink {
  constructor(name, price, size) {
    this.name = name;
    this.price = price;
    this.size = size;
}
  coffee() {
    return this.name + '에 샷 추가하기';
  }
}



  • 인스턴스 객체 생성
const soda = new Drink('soda', 500, 'tall');

console.log(soda);
>>Drink {name: 'soda', price: 500, size: 'tall'}

console.log(soda.coffee());
>>soda에 샷 추가하기



2. 자식 class 생성 (상속)



  • 클래스 Drink의 속성과 메서드를 상속받는 클래스 Coffee를 생성한다.
    : class 자식클래스 extends 부모클래스 {...}
    
  • 자식 클래스에서 부모 클래스의 생성자와 메서드를 참조할 때 super 키워드를 사용한다.
    super(...) : 부모 클래스의 생성자를 참조한다
    super.method : 부모 클래스 프로토타입 메소드를 참조한다
    
class Coffee extends Drink {
  //1. 속성 추가
  constructor(name, price, size, beans) {
    super(name, price, size); //부모클래스의 생성자를 참조한다.
    this.beans = beans;
  }
//2. Method Overriding
  coffee() {  
    return super.coffee() + '는 무료입니다.'; //부모클래스 프로토타입 메서드를 참조한다.
  }
};

생성자를 정의할 때 super 키워드가 this보다 먼저 나와야 부모클래스와 동일한 this value를 가질 수 있다.

  • 인스턴스 객체 생성
const latte = new Coffee('latte', 1000, 'tall', 'Brazil');

console.log(latte);
>Coffee {name: 'latte', price: 1000, size: 'tall', beans: 'Brazil'}

console.log(latte.coffee());
>latte에 샷 추가하기는 무료입니다.

상속을 통해 코드의 중복을 줄이고 재사용성을 높인다. (extends)
부모클래스에서 상속 받은 값을 필요에 따라 자식클래스 내부에서 변경할 수 있다. (super)
💡 Method Overriding : 부모클래스 method를 자식클래스에서는 다르게 구현하는 것 (다형성)



✔️ Object.create()

: 괄호안의 객체(부모)를 상속하는 새로운 객체(자식)를 만든다.

let drink = {name : 'drink', price : 1000, size: 'tall'};
let soda = Object.create(drink); // drink를 상속하는 객체 soda 생성



  • 객체 drink는 객체 soda프로토타입이다.
//생성자.isPrototypeOf(인스턴스객체)
drink.isPrototypeOf(soda)
>true


아직 soda 객체 내부에는 속성(키와 값)이 할당되지 않았다.
하지만 만약 이 상태에서 속성을 조회하면?

console.log(soda.price);
>1000

drink객체의 값이 나오는 것을 볼 수 있다.
프로토타입 체인으로 자식 객체에 없는 속성을 부모 객체에서 참조한 것이다.



💡 soda.name 값을 조회하고 변경해보자.

console.log(soda.name);
>drink //현재 부모 객체의 값이 나옴

soda.name = 'soda'; //soda의 name속성 정의
console.log(soda);
>{name: 'soda'}

console.log(drink);
>{name: 'drink', price: 1000, size: 'tall'} //soda에서만 적용된다.




✔️ DOM의 프로토타입

document.createElement() 메서드를 이용하여 element를 생성할 수 있다.
그렇게 생성된 요소의 .__proto__를 조회하면 상속받은 부모 클래스를 확인할 수 있다.

-> div요소는 HTMLDivElement 클래스의 인스턴스이다.

다시 이것의 .__proto__를 조회하며 부모 클래스를 타고 올라갈 수 있다.

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

div.__proto__
>HTMLDivElement {}

div.__proto__.__proto__
>HTMLElement {}

div.__proto__.__proto__.__proto__
>Element {}
...





더 공부할 것

  • 함수.call(호출할 객체, 함수의 매개변수)
    ex) sum.call(drink, 3)
    함수 내부의 this value는 호출한 객체가 된다.

  • apply


https://developer.mozilla.org/ko/docs/Learn/JavaScript/Objects/Classes_in_JavaScript#ecmascript_2015_%ED%81%B4%EB%9E%98%EC%8A%A4

profile
즐겁게 공부하고 꾸준히 기록하는 나의 프론트엔드 공부일지

0개의 댓글