Javascript - ES6 Class & super
2020. 7. 30. 11:30ㆍjavascript
1. Class란
JavaScript class는 ECMAScript 2015을 통해 소개되었으며, 기존 prototype 기반의 상속 보다 명료하게 사용할 수 있게 해준 것이지만, 중요한 것은 기존의 방법과 동일하지만 표현 방법이 달라진 것일 뿐이다!
2. 사용방법
//class 정의
class restaurant{
constructor(appet, main, drink){
this.appet = appet;
this.main = main;
this.drink = drink;
}
}
//class 사용방법
let my = new restaurant('soup', 'meet', 'beer');
my.appet // 'soup'
my.main // 'meet'
my.drink // 'beer'
//__proto__를 사용하면자신이 받은 객체의 정보를 볼 수 있다!(지금의 경우 Class restaurant의 정보)
my.__proto__
//{constructor: ƒ}
//constructor: class restaurant
//__proto__: Object
//Method 생성
restaurant.prototype.cook = function(){console.log('now cooking!')};
my.cook() // now cooking!
3. Class의 상속
상속이란 새로만든 객체가 다른 객체의 것을 받아서 사용하고 싶다면, 쓸 수 있는 방법이다. 위의 restaurant 클래스를 Franchise가 상속받아 보겠다.
//상속 방법
class Franchise extends restaurant{}
let my2 = new Franchise('vegetable', 'steak', 'wine');
//동일하게 constructor를 내려받을 시 super를 생략할 수 있다!
my2.appet //"vegetable"
my2.main //"steak"
my2.drink //"wine"
my2.cook() //now cooking!
4. super란
super는 한 객체가 다른 객체를 상속 받을때 객체의 부모가 가지고 있는 함수를 호출할 때 사용된다. 보통 그냥 받아도 위의 코드예시처럼 받을 수 있지만, '변경'을 필요로 할때 사용하면 좋다.
class Franchise2 extends restaurant{
cook(){
super.cook();
console.log('I finished cooking!');
}
}
let my3 = new Franchise2('vegetable','steak','wine');
my3.cook();
//now cooking!
//I finished cooking!
super()를 이렇게 사용시, 부모 객체에서 불러오기 때문에 constructor에서도 사용할 수도 있다.
'javascript' 카테고리의 다른 글
call, apply, bind (2) - apply (0) | 2020.08.28 |
---|---|
call, apply, bind (1) - call (0) | 2020.08.22 |
call, apply, bind를 시작하기 전에 this (0) | 2020.08.11 |
Callback function (0) | 2020.08.11 |
Javascript - Object Oriented Programming(OOP) (0) | 2020.07.29 |