자바스크립트는 상속이 이루어지는 개념은 간단한데 그것을 구현하는 코드가 상당히 장황하다. Object.create() 을 사용해도 장황한 건 마찬가진데 이를 보완하기 위해 ECMAScript6에서 class 스펙이 추가되었다. 클래스라고는 하지만 새로운 개념이 아니고 상속의 구현 원리는 기존과 동일한 내용으로 장황했던 코드를 간결하게 하는 숏컷이 추가됐다고 생각하면 된다.
- 코드가 간결해지고 이해하기 쉽게 바뀌었다 하더라도 이를 통해 만들어진 객체의 프로토타입 체인 연결 구조는 기존과 동일하고 또한 동일한 방식의 프로토타입 룩업으로 식별자를 찾아간다.
(ref: https://meetup.toast.com/posts/104)
class Parent {
constructor(name) {
this.name = name;
}
getName() {
return this.name;
}
}
class Child extends Parent {
constructor(name) {
super(name); // 생성자 빌려쓰기 대신....super 함수를 이용 한다.
this.age = 0;
}
getAge() {
return this.age;
}
}
▶ Inheritance Patterns - ES6 Class
• ES6의 Class는 기존 prototype 기반의 상속을 보다 명료하게 사용할 수 있도록 문법 제공
→ Syntatic Sugar (Syntatic Sugar : 읽고 표현하는것을 더 쉽게 하기 위해서 고안된 프로그래밍 언어 문법)
•JavaScript의 Class라는 개념이 없고, 기본적으로 Class 기반의 상속도 불가능. 대신 프로토타입(Prototype) 존재
→ JavaScript는 이 prototype을 기반으로 상속을 흉내내도록 구현해 사용
▷ Class
(ref: https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Classes)
•JavaScript에서 Class는 사실 함수
- class 선언식과 class 표현식 두가지 방법으로 정의가 가능
• JavaScript 엔진은 class 키워드를 만나면 Class 객체를 생성
- class는 클래스를 선언하는 키워드이고 Class 객체는 엔진이 class 키워드로 생성한 객체
* Class 선언
함수 선언과 달리 클래스 선언은 호이스팅이 일어나지 않기 때문에, 클래스를 사용하기 위해서는 먼저 선언 필요 (그렇지 않으면 ReferenceError 가 발생)
class People {
constructor(name) {
this.name = name;
}
say() {
console.log('My name is ' + this.name);
}
}
* Class 표현식
// Class 표현식은 이름을 가질 수도 있고(1) 갖지 않을 수도(2) 있습니다.
/* (1) */
const People = class People {
constructor(name) {
this.name = name;
}
say() {
console.log('My name is ' + this.name);
}
}
/* (2) */
const People = class {
constructor(name) {
this.name = name;
}
say() {
console.log('My name is ' + this.name);
}
}
※ Prototype 기반 상속(ES5)과 Class 기반 상속(ES6) 비교
/*** ES5 Prototype ***/
function Cat(name) {
this.name = name;
}
Cat.prototype.speak = function () { /* 생성자 함수가 있으면 Cat.prototype.speak와 같이
prototype에 메서드를 연결한 코드가 있습니다.*/
console.log(this.name + ' makes a noise.');
};
function Lion(name) {
// `super()` 호출
Cat.call(this, name);
}
// `Cat` 클래스 상속
Lion.prototype = Object.create(Cat.prototype); /* Object.create()를 통해 Cat.prototype에 연결된 메서드를
Lion.prototype.__proto__에 첨부 */
Lion.prototype.constructor = Lion; /* Lion.prototype에는 constructor가 연결되어 있는데,
prototype을 재할당했기 때문에 지워진 constructor를 다시 할당 */
// `speak()` 메서드 오버라이드
Lion.prototype.speak = function () {
Cat.prototype.speak.call(this);
console.log(this.name + ' roars.');
};
var lion = new Lion('Samba'); // lion은 생성자 함수(constructor)
lion.speak();
[결과]
Sambda makes a noise.
Sambda roars.
/*** ES6 Class ***/
class Cat {
constructor(name) {
this.name = name;
}
speak() {
console.log(this.name + ' makes a noise.');
}
}
class Lion extends Cat { // ES6에서는 extends 키워드로 상속을 구현
speak() {
super.speak();
console.log(this.name + ' roars.');
}
}
const lion = new Lion('Samba');
lion.speak();
[결과]
Sambda makes a noise.
Sambda roars.
→ Cat 상속받은 Lion 클래스의 구조는 prototype을 통해 상속을 구현한 Lion 생성자 함수의 구조와 일치
※ ES6 makes subclassing much easier as well with the introduction of the extends keyword.
▷ Super 키워드
: super 키워드는 ①부모 클래스의 constructor를 호출할 때, ②부모 클래스를 참조(Reference)할 때 사용
※ super ①메소드로 사용될 때, ②객체로 사용될 때 다르게 동작
// 부모 클래스
class Circle {
...
}
class Cylinder extends Circle {
constructor(radius, height) {
// ① super 메소드는 부모 클래스의 constructor를 호출하면서 인수를 전달한다.
super(radius);
this.height = height;
}
// 원통의 넓이: 부모 클래스의 getArea 메소드를 오버라이딩하였다.
getArea() {
// (원통의 높이 * 원의 둘레) + (2 * 원의 넓이)
// ② super 키워드는 부모 클래스(Base Class)에 대한 참조
return (this.height * super.getPerimeter()) + (2 * super.getArea());
}
// 원통의 부피
getVolume() {
// ② super 키워드는 부모 클래스(Base Class)에 대한 참조
return super.getArea() * this.height;
}
}
// 반지름이 2, 높이가 10인 원통
const cylinder = new Cylinder(2, 10);
•① super 메소드는 자식 class의 constructor 내부에서 부모 클래스의 constructor(super-constructor)를 호출(즉, 부모 클래스의 인스턴스를 생성)
- 자식 클래스의 constructor에서 super()를 호출하지 않으면 this에 대한 참조 에러(ReferenceError)가 발생
•② super 키워드는 부모 클래스(Base Class)에 대한 참조. 부모 클래스의 필드 또는 메소드를 참조하기 위해 사용
* Reference
https://meetup.toast.com/posts/104
쉽게 이해하는 자바스크립트 프로토타입 체인 : TOAST Meetup
쉽게 이해하는 자바스크립트 프로토타입 체인
meetup.toast.com
https://jongmin92.github.io/2017/06/18/JavaScript/class/#4
ES6 Class 파헤치기 - 92Hz
Index ES6 Class 문법 Class 정의 constructor Prototype 기반 상속(ES5)과 Class 기반 상속(ES6) 비교 super 키워드 static 키워드 마치며 ES6 Class 문법 JavaScript Class는 ECMAScript 6을 통해 소개되었습니다. ES6의 Class는 기존 prototype 기반의 상속을 보다 명료하게 사용할 수 있도록 문법을 제공합니다. 이를 Syntatic Sugar라고 부르기도 합니다.
jongmin92.github.io
https://jongmin92.github.io/2017/03/14/JavaScript/understand-prototype/
Prototype 이제는 이해하자 - 92Hz
Index prototype은 왜 어려울까? 객체(object)는 함수(function)로부터 시작된다 함수(function) 생성시 발생하는 일 객체(object) 생성시 발생하는 일 프로토타입 체인(Prototype Chain) 번외 prototype은 왜 어려울까? C++, Java와 같은 클래스 기반 객체지향 언어와 달리 자바스크립트는 프로토타입 기반 객체지향 언어입니다. 프로토타입을 사용하여 객체지향을 추구하기 때문에 자바스크립트를 사용함에 있어
jongmin92.github.io
“Super” and “Extends” In JavaScript ES6 - Understanding The Tough Parts
ES6 has made JavaScript look a lot simpler with the class syntax and its additional features. Today we are going to combine the class…
medium.com
https://poiemaweb.com/es6-class#82-super-%ED%82%A4%EC%9B%8C%EB%93%9C
Class | PoiemaWeb
자바스크립트는 프로토타입 기반(prototype-based) 객체지향형 언어다. 비록 다른 객체지향 언어들과의 차이점에 대한 논쟁들이 있긴 하지만, 자바스크립트는 강력한 객체지향 프로그래밍 능력들을 지니고 있다. 프로토타입 기반 프로그래밍은 클래스가 필요없는(class-free) 객체지향 프로그래밍 스타일로 프로토타입 체인과 클로저 등으로 객체 지향 언어의 상속, 캡슐화(정보 은닉) 등의 개념을 구현할 수 있다. 하지만 클래스 기반 언어에 익숙한 프로그래
poiemaweb.com
http://woowabros.github.io/experience/2017/12/01/es6-experience.html
신선함으로 다가온 ES6 경험 - 우아한형제들 기술 블로그
신선함으로 다가온 ES6 경험
woowabros.github.io
JavaScript 프로토타입 기반의 함수 Class (ES6)
안녕하세요 ! 오늘은 ES6에서 도입 된 Class에 대해 알아보겠습니다. 들어가기 전 이야기 드리고 싶은 부분이 있습니다. JavaScript는 프로토타입 기반 객체 지향 언어입니다. 모든 객체는 각 부모 역할을 담당하..
happycording.tistory.com
'CODESTATES > Immersive' 카테고리의 다른 글
[TIL] 1/13: HTTP, Server, API (0) | 2020.01.13 |
---|---|
DataStructure Reference (0) | 2020.01.09 |
[TIL] 1/3: Inheritance Patterns - 2. ES5 Prototype 기반 상속/ Object.create (0) | 2020.01.05 |
[TIL] 1/3: Inheritance Patterns - 1. ES6/ ES6 new features (0) | 2020.01.03 |
[TIL] 12/31: Time Complexity (0) | 2019.12.31 |