❗️주의 : 공부 중인 사람의 글입니다.
자바스크립트는 프로토타입 기반 언어이다.
자바스크립트에서 OOP 상속을 구현할 때 프로토타입 체인을 사용한다.
클래스 메서드 정의와 호출하는 과정을 보며
인스턴스객체.__proto__ === 클래스.prototype
라는 사실을 알 수 있었다.
자바스크립트에서 부모 클래스를 상속받을 때 extends
키워드를 사용한다.
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에 샷 추가하기
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를 자식클래스에서는 다르게 구현하는 것 (다형성)
: 괄호안의 객체(부모)를 상속하는 새로운 객체(자식)를 만든다.
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에서만 적용된다.
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